我想知道如何退出Python而不对输出进行跟踪转储。
我仍然希望能够返回错误代码,但我不想显示回溯日志。
我希望能够退出使用出口(数字)没有跟踪,但在异常(不是出口)的情况下,我想要跟踪。
我想知道如何退出Python而不对输出进行跟踪转储。
我仍然希望能够返回错误代码,但我不想显示回溯日志。
我希望能够退出使用出口(数字)没有跟踪,但在异常(不是出口)的情况下,我想要跟踪。
当前回答
import sys
sys.exit(1)
其他回答
您可能遇到了一个异常,并且程序因此退出(带有回溯)。因此,要做的第一件事是在干净地退出(可能带有消息,给出的示例)之前捕获该异常。
在你的主要动作中尝试这样做:
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()
# Pygame Example
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('IBM Emulator')
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj = (10, 10)
try:
while True: # main loop
DISPLAYSURF.fill(BLACK)
DISPLAYSURF.blit(textSurfaceObj, textRectObj)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
except SystemExit:
pass
比如import sys;sys.exit (0) ?
下面的代码将不会引发异常,并且将在没有回溯的情况下退出:
import os
os._exit(1)
请参阅此问题和相关答案了解更多细节。很惊讶为什么其他答案都这么复杂。
这也不会进行适当的清理,如调用清理处理程序,刷新stdio缓冲区等(感谢pabouk指出这一点)。
是什么
import sys
....
....
....
sys.exit("I am getting the heck out of here!")
没有追溯,而且更明确。