Exit code when python script has an unhandled exception

I need a method to run a python script file, and if the script does not work with an unhandled exception, python should exit with a non-zero exit code. My first attempt was something like this:

import sys if __name__ == '__main__': try: import <unknown script> except: sys.exit(-1) 

But this breaks a lot of scripts due to the often used __main__ protector. Any suggestions on how to do this correctly?

+7
source share
2 answers

Python already does what you ask:

 $ python -c "raise RuntimeError()" Traceback (most recent call last): File "<string>", line 1, in <module> RuntimeError $ echo $? 1 

After some changes from the OP, maybe you want:

 import subprocess proc = subprocess.Popen(['/usr/bin/python', 'script-name']) proc.communicate() if proc.returncode != 0: # Run failure code else: # Run happy code. 

Correct me if I'm confused here.

+11
source

if you want to run a script in a script, then the import is wrong; you can use exec if you only care about exceptions:

 namespace = {} f = open("script.py", "r") code = f.read() try: exec code in namespace except Exception: print "bad code" 

you can also compile code with

 compile(code,'<string>','exec') 

if you plan to execute the script more than once and execute the result in the namespace

or use a subprocess as described above if you need to capture the output generated by your script.

+1
source

All Articles