如何跳过系统退出发生未处理的异常时

2024-10-01 09:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

正如你所看到的,即使程序应该死了,它也会从坟墓里说出来。有没有办法在发生异常的情况下“注销”exitfunction?在

import atexit

def helloworld():
    print("Hello World!")

atexit.register(helloworld)

raise Exception("Good bye cruel world!")

输出

^{pr2}$

Tags: import程序registerhelloworlddefexception情况
3条回答

我真的不知道您为什么要这样做,但是您可以安装一个excepthook,每当出现未捕获的异常时,Python就会调用它,并在其中清除atexit模块中注册函数的数组。在

像这样:

import sys
import atexit

def clear_atexit_excepthook(exctype, value, traceback):
    atexit._exithandlers[:] = []
    sys.__excepthook__(exctype, value, traceback)

def helloworld():
    print "Hello world!"

sys.excepthook = clear_atexit_excepthook
atexit.register(helloworld)

raise Exception("Good bye cruel world!")

请注意,如果异常是从atexit注册的函数中引发的,那么它的行为可能会不正确(但是即使没有使用这个钩子,这种行为也会很奇怪)。在

如果你打电话

import os
os._exit(0)

退出处理程序将不会被调用,无论是您的还是由应用程序中其他模块注册的。在

除了调用os.\u exit()以避免注册的退出处理程序外,还需要捕获未处理的异常:

import atexit
import os

def helloworld():
    print "Hello World!"

atexit.register(helloworld)    

try:
    raise Exception("Good bye cruel world!")

except Exception, e:
    print 'caught unhandled exception', str(e)

    os._exit(1)

相关问题 更多 >