简体   繁体   English

当python脚本有未处理的异常时退出代码

[英]Exit code when python script has unhandled exception

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. 我需要一个方法来运行python脚本文件,如果脚本失败并带有未处理的异常,python应该以非零退出代码退出。 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. 但是由于经常使用的__main__守卫,它打破了很多脚本。 Any suggestions for how to do this properly? 有关如何正确执行此操作的任何建议?

Python already does what you're asking: Python已经做了你所要求的:

$ 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: 经过OP的一些编辑后,也许你想要:

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. 如果我在这里感到困惑,请纠正我。

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: 如果你只关心捕获异常,你可以使用exec:

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. 或者如上所述使用子进程,如果需要获取脚本生成的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM