发生未处理的异常时如何跳过 sys.exitfunc
题
正如您所看到的,即使程序应该已经死亡,它仍然会从坟墓中说话。有没有办法在出现异常时“取消注册”退出函数?
import atexit
def helloworld():
print("Hello World!")
atexit.register(helloworld)
raise Exception("Good bye cruel world!")
输出
Traceback (most recent call last):
File "test.py", line 8, in <module>
raise Exception("Good bye cruel world!")
Exception: Good bye cruel world!
Hello World!
解决方案
我真的不知道你为什么要这样做,但是你可以安装一个 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._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)
不隶属于 StackOverflow