python - 忽略在 __del__() 中打印到 stderr 的异常

标签 python

根据Python (2.7) documentation :

Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead

完全和绝对忽略 __del__() 中引发的异常的最 Pythonic 方法是什么——也就是说,不仅忽略异常,而且不打印任何内容。有没有比暂时将 stderr 重定向到空设备更好的方法?

最佳答案

我假设这是在您正在编写的 __del__() 函数中,如果是这样,您自己捕获异常并忽略它。

def __del__(self):
    try:
        # do whatever you need to here
    except Exception:
        pass

stderr 的日志记录仅适用于 __del__() 中的未捕获 异常。

关于python - 忽略在 __del__() 中打印到 stderr 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13977970/

相关文章:

python - 如何使用 Selenium 和 Python 定位元素并提取内部文本

python - Keras model.predict() 在第一次迭代时变慢然后变快

python - Strapi:连接到 MySQL

python - 将模块和应用程序安装到离线系统的规范方法

Python 语法和其他检查?

python - 安装.py : installing just a pth file?

python - 雪花 Pandas pd_writer用NULL写入表

python - 如何查找特定模块的包名称?

python - 使用 JSON 保存 Python 元组

数组与标量中的python赋值