[英]Passing NamedTemporaryFile to a subprocess on windows
tempfile.NamedTemporaryFile
的python文档说:
名称是否可以用于第二次打开文件,而命名的临时文件仍然是打开的,因此不同平台(它可以在Unix上使用;它不能在Windows NT或更高版本上使用)。
我有一个程序,作为prog input.txt
调用,我无法触及。 我想写一个python函数来给它一个字符串。
这里的各种方法并不常用:
from tempfile import NamedTemporaryFile
如果在Windows上合法,则不明显
with NamedTemporaryFile() as f: f.write(contents) subprocess.check_call(['prog', f.name]) # legal on windows?
可能会过早删除文件
with NamedTemporaryFile() as f: f.write(contents) f.close() # does this delete the file? subprocess.check_call(['prog', f.name])
不能正常清理
with NamedTemporaryFile(delete=False) as f: f.write(contents) # if this fails, we never clean up! try: subprocess.check_call(['prog', f.name]) finally: os.unlink(f.name)
有点难看
f = NamedTemporaryFile(delete=False) try: with f: f.write(contents) subprocess.check_call(['prog', f.name]) finally: os.unlink(f.name)
哪一项是正确的?
正如您所怀疑的那样,前三个变体都被破坏了 - 第一个变种将在Windows上抛出PermissionError
; 第二个确实过早地删除了文件; 第三个不能正确处理异常。
因此,您的第四个片段是正确的方法。
但是,正如你所说,这有点难看。 我建议将其包装在一个函数中,以提高可读性和可重用性:
import os
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
@contextmanager
def ClosedNamedTempfile(contents, mode='w'):
f = NamedTemporaryFile(delete=False, mode=mode)
try:
with f:
f.write(contents)
yield f.name
finally:
os.unlink(f.name)
这允许我们像这样使用它:
with ClosedNamedTempfile('foobar\n') as f:
subprocess.check_call(['prog', f])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.