如何异步获取子进程'stdout数据?

Max*_*rai 10 python subprocess asynchronous stdout

我为我的应用程序编写了一个简单的python脚本,并预定了一些快速命令,如make等.

我编写了一个运行系统命令的函数(linux):

def runCommand(commandLine):
    print('############## Running command: ' + commandLine)
    p = subprocess.Popen(commandLine, shell = True, stdout = subprocess.PIPE)
    print (p.stdout.read().decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

一切都很好,除了一些事情:

  • 我正在使用cmake,它的输出是彩色的.有没有机会在输出中保存颜色?

  • 我可以在流程完成后查看输出.例如,make运行很长一段时间但我只能在完全编译后看到输出.如何异步进行?

mat*_*per 12

我不确定颜色,但这里是如何一次轮询子进程的stdout一行:

import subprocess
proc = subprocess.Popen('cmake', shell=True, stdout=subprocess.PIPE)
while proc.poll() is None:
    output = proc.stdout.readline()
    print output
Run Code Online (Sandbox Code Playgroud)

不要忘记从st​​derr读取,因为我确信cmake会在那里发出信息.