【问题标题】:Python iterate over linux command output, line by line in real-timePython逐行实时迭代linux命令输出
【发布时间】:2015-10-07 06:59:53
【问题描述】:

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

import os

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

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

【问题讨论】:

    标签: python linux pipe


    【解决方案1】:

    while 语句中,您可以使用 subprocess 逐行读取,

    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
    

    【讨论】:

    • 我很确定您可以像任何其他类似文件的对象一样迭代 process.stdout
    【解决方案2】:
    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
    

    【讨论】:

    • 谢谢,这是最接近和最简单的使用方法!
    【解决方案3】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2021-12-10
      • 2020-03-12
      • 2013-12-26
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多