正如你所看到的,即使该计划应该已经死亡,它也会从坟墓中说出来。有没有办法在例外的情况下“取消注册”退出函数?
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!
答案 0 :(得分:5)
我真的不知道你为什么要这样做,但是你可以安装一个异常错误,只要引发了一个未捕获的异常,Python就会调用它,并清除{{1}中注册函数的数组}模块。
类似的东西:
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!")
已注册的函数引发异常,它可能会出现错误行为(但即使未使用此挂钩,行为也会很奇怪)。
答案 1 :(得分:0)
如果你打电话
import os
os._exit(0)
不会调用退出处理程序,也不会调用应用程序中其他模块注册的退出处理程序。
答案 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)