Python通过实时逐行迭代linux命令输出

时间:2015-10-07 06:59:54

标签: python linux pipe

我已经在python中看到了很多使用管道的方法,但是它们太复杂了,无法理解。我想要写的是这样的东西:

import os

for cmdoutput_line in os.system('find /'):
  print cmdoutput_line

在没有等待+ big-buffering命令输出的情况下实现它的最简单方法是什么?我不想在命令完成时等待,我只是想实时迭代输出。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

试试这个:

import subprocess

sp = subprocess.Popen('find /', shell=True, stdout=subprocess.PIPE)
results = sp.communicate()
print results