Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a python script from within python and also catch the exception

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 ?

like image 240
dumper Avatar asked Jun 23 '26 11:06

dumper


1 Answers

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)
like image 154
famousgarkin Avatar answered Jun 26 '26 02:06

famousgarkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!