我想知道如何退出Python而不对输出进行跟踪转储。
我仍然希望能够返回错误代码,但我不想显示回溯日志。
我希望能够退出使用出口(数字)没有跟踪,但在异常(不是出口)的情况下,我想要跟踪。
我想知道如何退出Python而不对输出进行跟踪转储。
我仍然希望能够返回错误代码,但我不想显示回溯日志。
我希望能够退出使用出口(数字)没有跟踪,但在异常(不是出口)的情况下,我想要跟踪。
当前回答
# 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(1)
比如import sys;sys.exit (0) ?
您可能遇到了一个异常,并且程序因此退出(带有回溯)。因此,要做的第一件事是在干净地退出(可能带有消息,给出的示例)之前捕获该异常。
在你的主要动作中尝试这样做:
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()
也许您正在尝试捕获所有异常,这是捕获由sys.exit()引发的SystemExit异常?
import sys
try:
sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
sys.exit(e)
except:
# Cleanup and reraise. This will print a backtrace.
# (Insert your cleanup code here.)
raise
一般来说,使用except:而不指定异常是一个坏主意。您将捕获所有您不想捕获的东西——比如SystemExit——而且它还可以掩盖您自己的编程错误。我上面的例子很愚蠢,除非你正在做一些关于清理的事情。你可以用:
import sys
sys.exit(1) # Or something that calls sys.exit().
如果你需要在不触发SystemExit的情况下退出:
import os
os._exit(1)
我这样做,在代码中运行在unittest和调用fork()。当fork进程引发SystemExit时,Unittest得到。这绝对是个特例!
# 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