获取用Bash在子壳中启动的Python脚本的退出代码。

问题描述 投票:0回答:1

我想每分钟运行一个 Bash 脚本 (通过 CRON 条目),以细化 (时间上) 的方式启动一系列 Python 脚本。

到目前为止,这就是我做的脚本。

# set the current date
DATE=`date +%Y-%m-%d`

# set the current system time (HH:MM)
SYSTIME=`date +%H-%M`

# parse all .py script files in the 'daily' folder
for f in daily/*.py; do
    if [[ -f $f ]]; then
        # set the script name
        SCRIPT=$(basename $f)

        # get the script time
        SCRTIME=`echo $SCRIPT | cut -c1-5`

        # execute the script only if its intended execution time and the system time match
        if [[ $SCRTIME == $SYSTIME ]]; then
            # ensure the directory exists
            install -v -m755 -d done/$DATE/failed

            # execute the script
            python3 evaluator.py $f > done/$DATE/daily-$SCRIPT.log &

            # evaluate the result
            if [ $? -eq 0 ]; then
                # move the script to the 'done' folder
                cp $f done/$DATE/daily-$SCRIPT
            else
                # log the failure
                mv done/$DATE/daily-$SCRIPT.log done/$DATE/failed/

                # move the script to the 'retry' folder for retrial
                cp $f retry/daily-$SCRIPT
            fi
        fi
    fi
done

假设我们有以下文件在一个叫 daily/ (用于每日执行)。

daily/08-00-script-1.py
daily/08-00-script-2.py
daily/08-05-script-3.py
daily/09-20-script-4.py

粒度执行的想法是,每分钟都有一个CRON任务运行这个脚本。我获取系统时间,提取每个脚本的执行时间,当系统和脚本文件的时间匹配时,就会交给Python。到目前为止,还算不错。

我知道这个脚本是不对的,因为它为每个要执行的脚本获取了一个子shell,但是下面的代码是错误的,因为我知道Bash在子shell调用时自动返回0(如果我在Google上搜索时没有看错的话),我需要的是让每个子shell执行下面的代码,这样,如果它失败了,就会被发送到另一个文件夹(retry/),它是由另一个Bash脚本控制的,每30分钟检查一次重试(它和这个脚本一样,减去检查部分)。

所以, 基本上, 我需要运行这个:

# evaluate the result
if [ $? -eq 0 ]; then
    # move the script to the 'done' folder
    cp $f done/$DATE/daily-$SCRIPT
else
    # log the failure
    mv done/$DATE/daily-$SCRIPT.log done/$DATE/failed/

    # move the script to the 'retry' folder for retrial
    cp $f retry/daily-$SCRIPT
fi

每执行一次subshell -ed就执行一次 我怎样才能用正确的方法来做呢?

bash cron exit-code subshell
1个回答
1
投票

Bash可能会对每个子shell的调用返回0,但如果你等待结果,那么你会得到结果(我没有看到安括号)。如果python3命令是转发脚本的退出代码,那么你的代码将工作。如果你的代码没有捕捉到错误,那么这是python3的错误,你需要创建错误通信。重定向stderr的输出可能会有帮助,但首先要验证你的代码是否正常。

© www.soinside.com 2019 - 2024. All rights reserved.