子进程直到命令comp才返回

2024-05-13 06:15:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从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

Tags: andtheimport命令outputiftimeis
2条回答

sar检测到其标准输出不是终端并缓冲其输出。它不会产生太多的输出,因此缓冲区没有足够的空间在超时之前被冲洗到管道中。在

如果安装GNU coreutils,可以使用stdbuf命令禁用标准输出的缓冲。(如果您通过自制软件安装,它将作为gstdbuf安装。)

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

我不确定是否有类似的解决方案使用macosx附带的工具

发件人:https://stackoverflow.com/a/17698359/16148

对于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

相关问题 更多 >