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

时间:2014-06-13 14:37:29

标签: python bash shell

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

4 个答案:

答案 0 :(得分:4)

如果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

答案 1 :(得分:1)

未捕获的异常将产生打印到标准错误的回溯。你能做的最好就是捕获它,然后尝试解析它。

if ! ./scriptA.py < "$var" 2> stderr.txt; then
  # Parse stderr.txt to see what exception was raised.
fi

答案 2 :(得分:1)

您应该在Python中重写shell脚本并将其合并到现有的Python脚本中。 您目前使用date命令执行的操作可以使用datetimetime模块完成。您使用findos.walk完成#! /usr/bin/python def scriptA(file_to_process): # the code currently in scriptA goes here; # modify it to read from `file_to_process` rather than `sys.stdin` def get_file_list(): # your bash logic to construct the file list goes here, # converted to Python as suggested above def main(): for filename in get_file_list(): sys.stderr.write("Processing {}...\n".format(filename)) try: scriptA(open(filename, "rt")) except SomeExceptionType as e: # handle exception... except SomeOtherExceptionType as e: # handle other kind of exception... sys.stderr.write("Done processing {}.\n".format(filename)) main() 所做的工作。

这是一个大纲:

{{1}}

答案 3 :(得分:0)

你可以玩一些重定向游戏:

# open file descriptor 3, pointing to the same destination as stdout
exec 3>&1

# run the script, 
# python's stderr goes to stdout so it can be captured in a variable
# python's stdout goes to file descriptor 3, displayed on the terminal
python_stderr=$( ./scriptA.py < "$var" 2>&1 1>&3 )

# close the file descriptor
exec 3>&-

然后你可以检查$ python_stderr的模式

case $python_stderr in
    "") echo "nothing on stderr" ;;
    *foo*) handle_foo_error ;;
    *bar*) handle_bar_error ;;
    *baz*) handle_baz_error ;;
esac