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)
如果需要具有名称的临时文件,则必须使用
NamedTemporaryFile
函数。然后您可以使用temp.name
。阅读 http://docs.python.org/library/tempfile.html了解详细信息。完整的例子。
更新:如注释中所述,这在windows中可能不起作用。对windows使用this解决方案
试试这个:
它只是打印临时文件的内容,但这应该给你一个正确的想法。请注意,在外部进程看到该文件之前,该文件已关闭(
f.close()
)。这很重要——它确保所有写操作都被正确刷新(而且,在Windows中,您不会锁定文件)。NamedTemporaryFile
实例通常在关闭后立即删除;因此delete=False
位。如果你想对这个过程进行更多的控制,你可以尝试
subprocess.Popen
,但是听起来commands.getoutput
对于你的目的来说已经足够了。相关问题 更多 >
编程相关推荐