3

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 ?

2
  • Is there a reason why you can't just import test1? Commented Dec 2, 2014 at 7:23
  • test1 is a standalone script which is run as cron job with certain arguments. So I wanted to run the script with system arguments without making script a module. Commented Dec 2, 2014 at 8:12

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This works great. But how about you want to execute a perl script within a python.
@dumper I don't think you can catch a Perl exception from Python. Languages are usually not directly interoperable like this. You should execute non-Python code as a process and check it's return value, e.g. using subprocess.check_call. This is a conventional way of process result communication, when 0 means successful execution and any other status code returned means an error. Of course the executed process should adhere to the convention and return useful status codes.
0

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

test1.py

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

test2.py

import test1

try:
    test1.test()
except
    whateveryouwannado

Comments

0

Use try except and use function call will be better,

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.