【发布时间】:2021-03-08 01:41:12
【问题描述】:
我在使用 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() 函数,但我可以更改其余代码。
【问题讨论】:
-
使用多个
with语句是否有效? -
with myfile() as f1: with myfile() as f2: # do something here我也得到与多个 with 语句相同的错误。 -
那么我认为错误不在 ExitStack 中,对吧?
标签: python with-statement contextmanager