Exit code when python script has unhandled excepti

2020-03-13 08:09发布

问题:

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?

回答1:

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.



回答2:

if you want to run a script within a script then import isn't the way; you could use exec if you only care about catching exceptions:

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

you can also compile the code first with

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

if you are planning to execute the script more than once and exec the result in the namespace

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