gpt4 book ai didi

python - 发生未处理的异常时如何跳过 sys.exitfunc

转载 作者:太空狗 更新时间:2023-10-30 02:50:44 25 4
gpt4 key购买 nike

如您所见,即使在程序本应死亡之后,它仍然在坟墓中说话。有没有办法在出现异常时“注销”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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com