在python中我见过很多使用管道的方法,但是它们太复杂了,难以理解。我想写这样的东西:
import os
for cmdoutput_line in os.system('find /'):
print cmdoutput_line
在没有等待+大缓冲命令输出的情况下,实现它的最简单方法是什么?我不想在命令完成时等待,我只想实时迭代输出。
在while语句中可以逐行读取子进程,
from subprocess import Popen, PIPE, STDOUT
process = Popen('find /', stdout = PIPE, stderr = STDOUT, shell = True)
while True:
line = process.stdout.readline()
if not line: break
print line
from subprocess import Popen, PIPE
def os_system(command):
process = Popen(command, stdout=PIPE, shell=True)
while True:
line = process.stdout.readline()
if not line:
break
yield line
if __name__ == "__main__":
for path in os_system("find /tmp"):
print path
试试这个:
import subprocess
sp = subprocess.Popen('find /', shell=True, stdout=subprocess.PIPE)
results = sp.communicate()
print results