[英]Run a python script from within python and also catch the exception
从python中运行python脚本并捕获异常。
File: test1.py
try:
a = 1/0
except:
raise
File: test2.py
import subprocess
subprocess.call('python test.py', shell=True)
如何运行test1.py并捕获test2.py中的ZeroDivisionError?
你可以用exec
实现这个:
with open('script.py') as f:
script = f.read()
try:
exec(script)
except ZeroDivisionError as e:
print('yay!', e)
你使用子进程有什么特别的原因吗? 我会这样做
test1.py
def test
try:
a = 1/0
except:
raise
test2.py
import test1
try:
test1.test()
except
whateveryouwannado
使用try except
和使用function
调用会更好,
test1.py
def solve():
try:
a = 1/0
except ZeroDivisionError as e:
print e.message
solve()
test2.py
import subprocess
subprocess.call('python foo.py', shell=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.