如何在发生未处理异常时跳过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!
2 个回答
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)
7
我不太明白你为什么想这么做,但你可以安装一个异常处理钩子,这样每当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
注册的函数中抛出的,可能会出现不正常的行为(不过即使没有使用这个钩子,行为也会很奇怪)。