pi.*_*pi. 4 python exception atexit
正如你所看到的,即使该计划应该已经死亡,它也会从坟墓中说出来.有没有办法在例外的情况下"取消注册"退出功能?
import atexit
def helloworld():
print("Hello World!")
atexit.register(helloworld)
raise Exception("Good bye cruel world!")
Run Code Online (Sandbox Code Playgroud)
输出
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!
Run Code Online (Sandbox Code Playgroud)
我真的不知道你为什么要这样做,但你可以安装一个异常的问题,每当引发一个未捕获的异常时它将由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!")
Run Code Online (Sandbox Code Playgroud)
请注意,如果从已atexit
注册的函数引发异常,它可能会表现不正确(但即使未使用此挂钩,行为也会很奇怪).
归档时间: |
|
查看次数: |
2983 次 |
最近记录: |