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

标签 python exception atexit

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

相关文章:

php - 在 PHP 中,捕获异常需要花费大量时间

ruby-on-rails - 如何测试是否有异常被拯救?

java - 为什么必须在 lambda 主体中用完整的代码块将 throw 语句括起来?

Python Numpy : Why is nparray[ i ][ j ] slower than nparray[ i , j]?

python - Pandas HDFStore : Saving and Retrieving a Series with Hierarchical Period Index

python:闭包和类

c - 如何从任何线程安全地使用 exit()

c - 为什么我不能将动态函数指针传递给 atexit()?

python - numpy 计算滞后于领导者时间戳和滞后时间戳之间

python - 多少面比较合理?