我正在尝试从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
sar
检测到其标准输出不是终端并缓冲其输出。它不会产生太多的输出,因此缓冲区没有足够的空间在超时之前被冲洗到管道中。在如果安装GNU coreutils,可以使用
stdbuf
命令禁用标准输出的缓冲。(如果您通过自制软件安装,它将作为gstdbuf
安装。)我不确定是否有类似的解决方案使用macosx附带的工具
发件人:https://stackoverflow.com/a/17698359/16148
对于Python 2:
相关问题 更多 >
编程相关推荐