Python:使用ExitStack避免多个with语句的最佳方法

2024-06-01 20:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码来说明我在哪里使用ExitStack而不是with语句

from contextlib import contextmanager
from contextlib import ExitStack
from tempfile import NamedTemporaryFile


@contextmanager
def myfile():
    temp_file = NamedTemporaryFile(suffix='.txt')
    temp_file.seek(0)
    yield temp_file
    os.unlink(temp_file.name)


with ExitStack() as stack:
    files = []
    for idx in range(5):
        files.append(stack.enter_context(myfile()))
    # do something with the files

上面的代码给出了5条错误消息,如下所示

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpbupwinzt.txt'

我是否以错误的方式使用ExitStack。做上述事情的正确方法是什么

注意:我不能更改myfile()函数,但我可以更改其余代码


Tags: 代码fromimporttxtstack错误withfiles
1条回答
网友
1楼 · 发布于 2024-06-01 20:25:32

我想我找到了一个解释。从docs开始:

[A TemporaryFile] will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected).

但是,您正在取消程序中文件的链接(第myfile行的最后一行)。当测试程序结束时,垃圾收集无法关闭和取消文件链接,并打印错误。换句话说,错误不会发生在with语句中

一个简单的解决方案是禁用自动删除:

NamedTemporaryFile(suffix='.txt', delete=False)

但是,我认为新文件上的seek(0)是不必要的,整个myfile不做NamedTemporaryFile还没有做的事情,因此您可以直接使用它:

with ExitStack() as stack:
    files = []
    for idx in range(5):
        files.append(stack.enter_context(NamedTemporaryFile(suffix='.txt')))

相关问题 更多 >