Run python script from inside python and also catch the exception

Run the 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 do I run test1.py and also catch the ZeroDivisionError in test2.py?

+3


source to share


3 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)

      

+2


source


Is there a specific reason why you are using a subprocess? I would do it this way.

test1.py

def test
    try:
        a = 1/0
    except:
        raise

      



test2.py

import test1

try:
    test1.test()
except
    whateveryouwannado

      

0


source


It will be better to use try except

and use the function

call,

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)

      

0


source







All Articles