【问题标题】:how to make sure io module isn't shutdown before garbage collection on close如何确保 io 模块在关闭垃圾收集之前没有关闭
【发布时间】:2021-05-05 14:14:19
【问题描述】:

我有一个带有__del__ 方法的对象。我希望在解释器关闭时调用此方法。 __del__ 方法将打开并写入特定文件。在全局垃圾回收之前,io 模块似乎已关闭。

#!/usr/bin/env python3
class Foo:
    def __del__(self):
        with open('/tmp/doge_poop', 'w') as f:
            f.write('corn kernel')
foo=Foo()

运行上述 MWE 会得到以下结果:

Exception ignored in: <function Foo.__del__ at 0x7f4984176310>
Traceback (most recent call last):
  File "b.py", line 4, in __del__
NameError: name 'open' is not defined

【问题讨论】:

  • 我尝试添加 foo 的成员 self.open=open,再次失败。

标签: python garbage-collection


【解决方案1】:

找到了一条路:

#!/usr/bin/env python3
from atexit import register
class Foo:
    def __del__(self):
        with open('/tmp/doge_poop', 'w') as f:
            f.write('corn kernel')
            print("delete!")
foo=Foo()

@register
def _atexit():
    global foo
    del foo

由群组https://t.me/py_zh_real 中的一名成员提供帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2023-01-12
    • 2010-09-10
    • 2011-05-27
    • 2015-06-10
    • 2013-06-05
    • 1970-01-01
    相关资源
    最近更新 更多