我有一个
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