2015-11-20 21 views
1

我想從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 

回答

1

sar檢測到其標準輸出不是終端並緩衝其輸出。它不會產生太多的輸出,所以緩衝區沒有足夠的空間在管道超時之前刷新到管道。

如果你安裝GNU的coreutils,您可以使用stdbuf命令禁用緩衝標準輸出。

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

我不知道(如果您是通過自制安裝它,它安裝爲gstdbuf。)如果使用的工具包括在Mac OS X上

+0

這看起來像我的問題是,我似乎無法安裝它,但它應該通過coreutils安裝。我找到了描述這個工具的http://apple.stackexchange.com/questions/193141/to-use-stdbuf-from-homebrews-coreutils。 – user1601716

+0

後'沖泡安裝coreutils',你需要使用'gstdbuf';該軟件包將所有命令名加上'g'作爲前綴以避免與標準工具發生衝突('gls'而不是'ls'等''stdbuf'不會發生衝突,但顯然打包者希望保持一致。) – chepner

+0

有安裝coreutils的問題,看起來像一個錯誤'make install',有一個無限名稱的文件:(但這看起來是問題,我現在可以解決這個問題。謝謝! – user1601716

0

從: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 
+0

不工作的可比的解決方案,代碼更乾淨,但sar命令仍在等待,直到它開始打印之前完成。 – user1601716

+0

@chepner其實不是。見:http://bugs.python.org/issue3907 –

相關問題