在shell scrip中捕获python脚本引发的异常

2024-06-01 03:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件echotxt脚本内容datevarshell
3条回答

如果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脚本中。 当前使用date命令执行的操作可以使用^{}^{}模块完成。你用find做的事情可以用^{}^{}来做。

这里有一个大纲:

#! /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()

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

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

相关问题 更多 >