从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?
答案 0 :(得分:2)
您可以使用exec
:
with open('script.py') as f:
script = f.read()
try:
exec(script)
except ZeroDivisionError as e:
print('yay!', e)
答案 1 :(得分:0)
您使用子进程有特殊原因吗? 我会这样做的
test1.py
def test
try:
a = 1/0
except:
raise
test2.py
import test1
try:
test1.test()
except
whateveryouwannado
答案 2 :(得分:0)
使用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)