子进程直到命令完成才返回

subprocess not returning until command complete

我正在尝试从 bash 命令获取实时输出,这样我就可以更轻松地处理数据。

在此代码中,命令 iostat 1 工作正常并在 1 秒打印输出。命令 sar -u 1 20 按预期在命令行上运行(每秒打印 1 行,最多 20 行),等待命令完成约 20 秒,然后以 0.1 秒的延迟打印每行。

我正计划 运行 无限期地执行这些命令,并且需要这部分工作。有什么想法吗?我在 OSX.

import subprocess
import time

# run a command and constantly check for new output, if you find it, print it and continue
# if the command is done, break out
try:
    command="sar -u 1 20"
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    while True:
        time.sleep(.1) # so i don't kill the cpu on the machine i'm checking
        output = process.stdout.readline()
        #if process.poll() is not None:
        #    break
        if output:
            print output.strip()
except KeyboardInterrupt:
    print 'Exiting...'
return_code = process.poll()
print return_code

来自:

对于 Python 2:

from subprocess import Popen, PIPE

p = Popen(["cmd", "arg1"], stdout=PIPE, bufsize=1)
with p.stdout:
    for line in iter(p.stdout.readline, b''):
        print line,
p.wait() # wait for the subprocess to exit

sar 检测到它的标准输出不是终端并缓冲它的输出。它不会产生太多输出,因此缓冲区没有填满,无法在超时之前刷新到管道。

如果安装了 GNU coreutils,则可以使用 stdbuf 命令禁用标准输出的缓冲。 (如果你通过 Homebrew 安装它,它安装为 gstdbuf。)

command = "stdbuf -o 0 sar -u 1 20"

我不确定是否有使用 Mac OS X 中包含的工具的类似解决方案。