Reputation: 91
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
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
Upvotes: 2
Views: 4083
Reputation: 1699
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
Upvotes: 6
Reputation: 1550
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.
Upvotes: 0