无论如何我可以写入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
小智 34
如果需要带名称的临时文件,则必须使用该NamedTemporaryFile功能.然后你可以使用temp.name.有关详细信息,请阅读
http://docs.python.org/library/tempfile.html.
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可能就足够了.