【发布时间】:2015-11-20 15:56:22
【问题描述】:
我正在尝试从 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 bash subprocess