gpt4 book ai didi

python - 在shell脚本中捕获python脚本抛出的异常

转载 作者:太空狗 更新时间:2023-10-29 23:59:00 37 4
gpt4 key购买 nike

我有一个 shell 脚本,它打开一个文件并将它传递给 python 脚本来处理它。因此,如果文件有任何问题(例如,文件内容不是成功执行 python 脚本所需的格式),则 python 脚本会抛出异常。由于我的目标是使用 python 脚本处理 N 个文件。我需要知道导致脚本中断的文件是哪个。我阅读了如何捕获命令执行抛出的异常。 http://linuxcommand.org/wss0150.php .但在我的例子中,它是抛出异常的 python 脚本,我需要在 shell 脚本中知道抛出了什么异常。谁能帮我解决这个问题?

下面是代码片段:

#!/bin/bash
yesterday=$(date --date "yesterday" "+%y%m%d")
ftoday=$(date --date "today" "+%m-%d-%Y")
year=$(date "+%Y")
fileList=$(find C:/logdata/$year/$ftoday/ -iname "*"$yesterday".log")
for var in $fileList
do
echo -e "\n START Processing File : $var" >> shelltestlog.txt
cat $var| ./scriptA.py
echo -e "\n END Processing File : $var" >> shelltestlog.txt
done

最佳答案

如果您的 python 脚本在遇到异常时返回非零错误级别,您可以使用 || { } 记录消息:

./scriptA.py < "$file" || {
printf "\n Python script scriptA.py failed with file \"%s\".\n" "$file" >> shelltestlog.txt
}

实际上我首先尝试简化您的代码:

#!/bin/bash

yesterday=$(date --date "yesterday" "+%y%m%d")
ftoday=$(date --date "today" "+%m-%d-%Y")
year=$(date "+%Y")

readarray -t filesList < <(find C:/logdata/$year/$ftoday/ -iname "*"$yesterday".log")

for file in "${filesList[@]}"; do
printf "\n START Processing File : %s\n" "$file" >> shelltestlog.txt
./scriptA.py < "$file" || {
printf "\n Python script scriptA.py failed with file \"%s\".\n" "$file" >> shelltestlog.txt
}
printf "\n END Processing File : %s\n" "$file" >> shelltestlog.txt
done

关于python - 在shell脚本中捕获python脚本抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24207916/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com