2

I am running python script from another python file. is there a way I can know if an eception occurred in the second script?

EX: script1.py calls script2.py python script2. py -arguments How can script1 know if an exception occurred in script2?

run.py

import subprocess

subprocess.call("python test.py -t hi", shell=True)

test.py

import argparse
print "testing exception"

parser = argparse.ArgumentParser(description='parser')
parser.add_argument('-t', "--test")

args = parser.parse_args()

print args.test
raise Exception("this is an exception")

Thanks

0

2 Answers 2

6

When a Python program throws an Exception, the process returns a non-zero return code. Subprocess functions like call will return the return code by default. So, to check if an exception occurred, check for a non-zero exit code.

Here is an example of checking the return code:

    retcode = subprocess.call("python test.py", shell=True)
    if retcode == 0:
        pass  # No exception, all is good!
    else:
        print("An exception happened!")

Another method would be to use subprocess.check_call, which throws a subprocess.CalledProcessError exception on a non-zero exit status. An example:

try:
    subprocess.check_call(["python test.py"], shell=True)
except subprocess.CalledProcessError as e:
    print("An exception occured!!")

If you need to know which exception occurred in your test program, you can change the exception using exit(). For example, in your test.py:

try:
    pass  # all of your test.py code goes here
except ValueError as e:
    exit(3)
except TypeError as e:
    exit(4)

And in your parent program:

retcode = subprocess.call("python test.py", shell=True)
if retcode == 0:
    pass  # No exception, all is good!
elif retcode == 3:
    pass  # ValueError occurred
elif retcode == 4:
    pass  # TypeError occurred
else:
    pass  # some other exception occurred
Sign up to request clarification or add additional context in comments.

1 Comment

@user3330263 updated answer to reflect your example code
0

Probably the best method is to make script2 an actual module, import what you want from it into script1, then use the existing try/except mechanic. But perhaps that's not an option? Otherwise I think what gets returned from os.system would probably include what you need.

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.