Exit code when python script has unhandled exception

混江龙づ霸主 提交于 2019-12-01 01:00:44

问题


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.



来源:https://stackoverflow.com/questions/5456157/exit-code-when-python-script-has-unhandled-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!