gpt4 book ai didi

python - 删除临时文件的上下文管理器

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:28 26 4
gpt4 key购买 nike

我正在尝试编写上下文管理器以在处理后有条件地清理临时文件。简化:

import os
from contextlib import contextmanager
from subprocess import Popen
from tempfile import NamedTemporaryFile


@contextmanager
def temp(cleanup=True):
tmp = NamedTemporaryFile(delete=False)
try:
yield tmp
finally:
cleanup and os.remove(tmp.name)

with temp() as tmp:
tmp.write(b'Hi')
p = Popen(['cmd', '/c', 'type', tmp.name])
p.wait()

尝试这个脚本引发:

Traceback (most recent call last):
File "C:\temp\test.py", line 18, in <module>
p.wait()
File "C:\Python35\lib\contextlib.py", line 66, in __exit__
next(self.gen)
File "C:\temp\test.py", line 13, in temp
cleanup and os.remove(tmp.name)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Temp\\tmp79su99sg'

我希望 tempfile 在 with 语句循环结束时被释放,但显然不是。

最佳答案

您可以使用 NamedTemporaryFile作为上下文管理器:

from tempfile import NamedTemporaryFile

with NamedTemporaryFile() as tmp:
tmp.write(b'Hi')
p = Popen(['cmd', '/c', 'type', tmp.name])
p.wait()
# Here the file is closed and thus deleted

关于python - 删除临时文件的上下文管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38005298/

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