gpt4 book ai didi

garbage-collection - 您如何管理临时目录以确保在程序关闭时将其删除?

转载 作者:太空狗 更新时间:2023-10-29 19:32:28 27 4
gpt4 key购买 nike

我正在使用一个临时目录,我想确保它在程序关闭时被删除(无论程序是否成功)。我正在使用 tempfile.mkdtemp 创建目录并将创建的字符串放入 str 的子类中,该子类删除其 __del__ 上的目录命令:

import shutil
import tempfile

class TempDir(str):
""" container for temporary directory.
Deletes directory when garbage collected/zero references """
def __del__(self):
shutil.rmtree(self.__str__(), onerror=my_error_fn)

dbdir = TempDir(tempfile.mkdtemp())

以下是我不确定的地方:如果程序关闭或发生 KeyboardInterrupt,Python 会自动删除/垃圾收集所有变量吗?如果没有,我如何确保该目录被删除?

关于creating destructor methods in Python的相关信息.似乎只要 TempDir 对象不引用任何其他东西,使用 __del__ 来破坏它应该没问题。

最佳答案

我不会使用 __del__ 方法,语义不可靠,并且可能会干扰垃圾回收。使用上下文管理器:定义一个 __enter____exit__ 方法,并将对象的使用放在 with 语句中。它很清楚,很明确,而且可以毫无顾虑地工作。

或者,另一种制作上下文管理器的方法:

@contextlib.contextmanager
def tempdir(prefix='tmp'):
"""A context manager for creating and then deleting a temporary directory."""
tmpdir = tempfile.mkdtemp(prefix=prefix)
try:
yield tmpdir
finally:
shutil.rmtree(tmpdir)

关于garbage-collection - 您如何管理临时目录以确保在程序关闭时将其删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10965479/

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