擅长:python、mysql、java
<p>从python3.2开始,<code>Popen</code>是一个上下文管理器。在</p>
<p>从<a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.</p>
</blockquote>
<p>这应该能满足你的需要。在</p>
<p>这是来自标准库<code>subprocess.py</code>的相关部分
在Python 3.4中:</p>
<pre><code>def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
if self.stdin:
self.stdin.close()
# Wait for the process to terminate, to avoid zombies.
self.wait()
</code></pre>
<p>现在您可以在Python2.7中使用了</p>
^{2}$