如您所见,即使在程序本应死亡之后,它仍然在坟墓中说话。有没有办法在出现异常时“注销”exitfunction?
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
注册函数中引发异常,它可能会出现错误行为(但即使未使用此 Hook ,行为也会很奇怪)。
关于python - 发生未处理的异常时如何跳过 sys.exitfunc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/80993/