从tempfi创建和读取

2024-04-24 02:46: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()

Tags: nameimport命令closedatasometempfiletemp
3条回答

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

完整的例子。

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解决方案

试试这个:

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对于你的目的来说已经足够了。

相关问题 更多 >