我有一个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
Run Code Online (Sandbox Code Playgroud)
如果您的 python 脚本在出现异常时返回非零错误级别,您可以使用以下方式|| { }记录消息:
./scriptA.py < "$file" || {
printf "\n Python script scriptA.py failed with file \"%s\".\n" "$file" >> shelltestlog.txt
}
Run Code Online (Sandbox Code Playgroud)
我实际上首先尝试简化您的代码:
#!/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
Run Code Online (Sandbox Code Playgroud)