擅长:python、mysql、java
<p>只要命令输出行,您就可以使用<a href="https://docs.python.org/3/library/functions.html#iter" rel="noreferrer">iter</a>处理这些行:<code>lines = iter(fd.readline, "")</code>。下面是一个完整的示例,展示了一个典型的用例(感谢@jfs的帮助):</p>
<pre><code>from __future__ import print_function # Only Python 2.x
import subprocess
def execute(cmd):
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, cmd)
# Example
for path in execute(["locate", "a"]):
print(path, end="")
</code></pre>