在调用另一个脚本的Python脚本中捕获异常
我在一个Python文件中运行另一个Python脚本。有没有办法让我知道第二个脚本中是否发生了异常?
举个例子:script1.py 调用 script2.py,命令是 python script2.py -arguments。那么,script1 怎么知道 script2 中是否发生了异常呢?
run.py
import subprocess
subprocess.call("python test.py -t hi", shell=True)
test.py
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")
谢谢
2 个回答
0
最好的办法可能是把script2变成一个真正的模块,然后把你需要的东西从它里面导入到script1中,这样就可以使用现有的try/except机制来处理错误了。不过,也许这样做不是一个可行的选择?如果不是的话,我觉得os.system返回的内容可能会包含你需要的信息。
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!")
另一种方法是使用subprocess.check_call,当返回码是非零时,它会抛出一个subprocess.CalledProcessError异常。这里有个例子:
try:
subprocess.check_call(["python test.py"], shell=True)
except subprocess.CalledProcessError as e:
print("An exception occured!!")
如果你想知道在你的测试程序中发生了什么异常,可以通过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)
然后在你的父程序中:
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