创造&从tempfile中读取

时间:2011-03-17 19:39:24

标签: python

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

import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()

4 个答案:

答案 0 :(得分:81)

完整的例子。

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])

更新:如评论中所述,这可能无法在Windows中使用。对Windows使用this解决方案

答案 1 :(得分:31)

如果您需要具有名称的临时文件,则必须使用NamedTemporaryFile功能。然后你可以使用temp.name。读 http://docs.python.org/library/tempfile.html了解详情。

答案 2 :(得分:18)

试试这个:

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)

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

如果您想要更好地控制该过程,可以尝试subprocess.Popen,但听起来commands.getoutput可能足以满足您的需要。

答案 3 :(得分:1)

改为使用NamedTemporaryFile及其成员name。由于Unix filesystems的工作方式,常规TemporaryFile甚至不能保证有名称。

相关问题