在调用另一个脚本的 python 脚本中捕获异常

use*_*263 2 python exception

我正在从另一个 python 文件运行 python 脚本。有没有办法知道第二个脚本中是否发生了eception?

例如:script1.py 调用 script2.py python script2。py -arguments 脚本 1 如何知道脚本 2 中是否发生异常?

运行文件

import subprocess
Run Code Online (Sandbox Code Playgroud)

subprocess.call("python test.py -t hi", shell=True)

测试文件

import argparse
print "testing exception"

parser = argparse.ArgumentParser(description='parser')
parser.add_argument('-t', "--test")

args = parser.parse_args()

print args.test
raise Exception("this is an exception")
Run Code Online (Sandbox Code Playgroud)

谢谢

Ole*_*leg 6

当 Python 程序抛出异常时,该进程会返回一个非零返回码。call默认情况下,子进程函数会返回返回码。因此,要检查是否发生异常,请检查非零退出代码。

以下是检查返回码的示例:

    retcode = subprocess.call("python test.py", shell=True)
    if retcode == 0:
        pass  # No exception, all is good!
    else:
        print("An exception happened!")
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用subprocess.check_call,它会在非零退出状态时引发 subprocess.CalledProcessError 异常。一个例子:

try:
    subprocess.check_call(["python test.py"], shell=True)
except subprocess.CalledProcessError as e:
    print("An exception occured!!")
Run Code Online (Sandbox Code Playgroud)

如果需要知道测试程序中发生了哪个异常,可以使用 exit() 更改异常。例如,在您的 test.py 中:

try:
    pass  # all of your test.py code goes here
except ValueError as e:
    exit(3)
except TypeError as e:
    exit(4)
Run Code Online (Sandbox Code Playgroud)

在你的父程序中:

retcode = subprocess.call("python test.py", shell=True)
if retcode == 0:
    pass  # No exception, all is good!
elif retcode == 3:
    pass  # ValueError occurred
elif retcode == 4:
    pass  # TypeError occurred
else:
    pass  # some other exception occurred
Run Code Online (Sandbox Code Playgroud)