发生未处理的异常时如何跳过 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!
As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?
import atexit
def helloworld():
print("Hello World!")
atexit.register(helloworld)
raise Exception("Good bye cruel world!")
outputs
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了调用 os._exit() 以避免注册退出处理程序之外,您还需要捕获未处理的异常:
In addition to calling os._exit() to avoid the registered exit handler you also need to catch the unhandled exception:
我真的不知道你为什么要这样做,但是你可以安装一个 excepthook,每当引发未捕获的异常时,Python 都会调用它,并清除 atexit 中注册函数的数组。 > 模块。
类似这样的事情:
请注意,如果从
atexit
注册函数引发异常,它可能会表现不正确(但即使不使用此钩子,行为也会很奇怪)。I don't really know why you want to do that, but you can install an excepthook that will be called by Python whenever an uncatched exception is raised, and in it clear the array of registered function in the
atexit
module.Something like that :
Beware that it may behave incorrectly if the exception is raised from an
atexit
registered function (but then the behaviour would have been strange even if this hook was not used).