如何从Python退出而无需追溯? [英] How to exit from Python without traceback?
问题描述
我想知道如何在不对输出进行回溯转储的情况下退出Python.
I would like to know how to I exit from Python without having an traceback dump on the output.
我仍然希望能够返回错误代码,但是我不想显示回溯日志.
I still want want to be able to return an error code but I do not want to display the traceback log.
我希望能够使用exit(number)
退出而不进行跟踪,但是如果发生异常(不是退出),我希望进行跟踪.
I want to be able to exit using exit(number)
without trace but in case of an Exception (not an exit) I want the trace.
推荐答案
您大概遇到了异常,因此程序正在退出(带有追溯).因此,要做的第一件事是在干净退出之前捕获该异常(也许带有一条消息,给出示例).
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).
在您的main
例程中尝试类似的操作:
Try something like this in your main
routine:
import sys, traceback
def main():
try:
do main program stuff here
....
except KeyboardInterrupt:
print "Shutdown requested...exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()
这篇关于如何从Python退出而无需追溯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!