当引发异常时,设置Python中的退出代码 [英] Setting exit code in Python when an exception is raised

查看:199
本文介绍了当引发异常时,设置Python中的退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ cat e.py
raise Exception
$ python e.py
Traceback (most recent call last):
  File "e.py", line 1, in <module>
    raise Exception
Exception
$ echo $?
1

我想将此退出代码从1更改为3,同时仍然将全堆栈跟踪。这是最好的方法?

I would like to change this exit code from 1 to 3 while still dumping the full stack trace. What's the best way to do this?

推荐答案

看看 traceback 模块。您可以执行以下操作:

Take a look at the traceback module. You could do the following:

import sys, traceback

try:
  raise Exception()
except:
  traceback.print_exc()
  sys.exit(3)

这将写回溯到标准错误,并退出与代码3。

This will write traceback to standard error and exit with code 3.

这篇关于当引发异常时,设置Python中的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆