[英]Getting the exit code of a Python script launched in a subshell with Bash
我想每分鍾運行一次 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 可能會為每個子 shell 調用返回 0,但是如果您等待結果,那么您將得到結果(我看不到 & 符號)。 如果 python3 命令正在中繼腳本的退出代碼,那么您的代碼將起作用。 如果你的代碼沒有捕捉到錯誤,那就是 python3 的問題,你需要創建錯誤通信。 重定向 stderr 的 output 可能會有所幫助,但首先要確認您的代碼不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.