擅长:python、mysql、java
<p>试试这个:</p>
<pre><code>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)
</code></pre>
<p>它只是打印临时文件的内容,但这应该给你一个正确的想法。请注意,在外部进程看到该文件之前,该文件已关闭(<code>f.close()</code>)。这很重要——它确保所有写操作都被正确刷新(而且,在Windows中,您不会锁定文件)。<code>NamedTemporaryFile</code>实例通常在关闭后立即删除;因此<code>delete=False</code>位。</p>
<p>如果你想对这个过程进行更多的控制,你可以尝试<code>subprocess.Popen</code>,但是听起来<code>commands.getoutput</code>对于你的目的来说已经足够了。</p>