Run a python script from within python and also catch the exception.
File: test1.py
try:
a = 1/0
except:
raise
File: test2.py
import subprocess
subprocess.call('python test.py', shell=True)
How can I run test1.py and also catch the ZeroDivisionError in test2.py ?
You can achieve this with exec:
with open('script.py') as f:
script = f.read()
try:
exec(script)
except ZeroDivisionError as e:
print('yay!', e)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With