从tempfile创建和读取

DGT*_*DGT 45 python

无论如何我可以写入tempfile并将其包含在命令中,然后关闭/删除它.我想执行命令,例如:some_command/tmp/some-temp-file.
提前谢谢了.

import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()
Run Code Online (Sandbox Code Playgroud)

bal*_*lki 82

完整的例子.

import tempfile
with tempfile.NamedTemporaryFile() as temp:
    temp.write('Some data')
    if should_call_some_python_function_that_will_read_the_file():
       temp.seek(0)
       some_python_function(temp)
    elif should_call_external_command():
       temp.flush()
       subprocess.call(["wc", temp.name])
Run Code Online (Sandbox Code Playgroud)

更新:如评论中所述,这可能无法在Windows中使用.使用解决方案适用于Windows

  • 只是想补充一点,如果命令被某些Python代码(如函数调用)替换,请确保你执行temp.seek(0),所以如果该函数试图读取内容,它将不会是空的. (11认同)
  • +1使用_with_.有没有理由说明[文档](https://docs.python.org/2/library/tempfile.html)中的示例不使用_with_? (3认同)
  • 请确保您从[docs](https://docs.python.org/3.4/library/tempfile.html#tempfile.NamedTemporaryFile)中考虑这一点:"该名称是否可用于再次打开文件,而命名的临时文件仍然是打开的,*因平台而异*(它可以在Unix上使用;它不能在Windows NT或更高版本上使用)." 请注意,使用`with`语句会在调用`command`时保持tempfile处于打开状态,因此您的代码的可移植性会受到影响. (2认同)

小智 34

如果需要带名称的临时文件,则必须使用该NamedTemporaryFile功能.然后你可以使用temp.name.有关详细信息,请阅读 http://docs.python.org/library/tempfile.html.

  • 确保在传递给some_command之前刷新文件 (10认同)
  • @balki或者你可以通过`bufsize = 0`来使它无缓冲. (2认同)

pho*_*oji 19

试试这个:

import tempfile
import commands
import os

commandname = "cat"

f = tempfile.NamedTemporaryFile(delete=False)
f.write("oh hello there")
f.close() # file is not immediately deleted because we
          # used delete=False

res = commands.getoutput("%s %s" % (commandname,f.name))
print res
os.unlink(f.name)
Run Code Online (Sandbox Code Playgroud)

它只打印临时文件的内容,但这应该给你正确的想法.请注意,在f.close()外部进程看到之前,文件已关闭().这很重要 - 它确保所有的写操作都被正确刷新(并且在Windows中,您没有锁定文件).NamedTemporaryFile实例通常在关闭后立即删除; 因此delete=False有点.

如果你想要更多地控制这个过程,你可以试试subprocess.Popen,但听起来commands.getoutput可能就足够了.

  • 这个答案(特别是`delete = False`和`close()`)是Windows案例的关键信息.谢谢. (2认同)