Exit code when python script has unhandled exception

pehrs picture pehrs · Mar 28, 2011 · Viewed 17.3k times · Source

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

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

But it breaks a lot of scripts, due to the __main__ guard often used. Any suggestions for how to do this properly?

Answer

Thanatos picture Thanatos · Mar 28, 2011

Python already does what you're asking:

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

After some edits from the OP, perhaps 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 am confused here.