2011-11-02 71 views
7

我有一個相當長的運行作業,運行幾分鐘然後重新啓動。任務輸出我捕獲像這樣的各種信息:如何捕獲輸出並使用Python同時顯示它?

output = subprocess.Popen(cmd,stdout=subprocess.PIPE).communicate() 

事情是,我一次只能得到整個輸出。我想顯示輸出爲程序發送到標準輸出,同時仍然推回到緩衝區(我需要檢查輸出是否存在一些字符串)。在Ruby中我會做這樣的:

IO.popen(cmd) do |io| 
    io.each_line do |line| 
    puts line 
    buffer << line 
    end 
end 

回答

5

你可以嘗試這樣的事情:

cmd = ["./my_program.sh"] 
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE) # launch the process 
while p.poll() is None:   # check if the process is still alive 
    out = p.stdout.readline() # if it is still alive, grab the output 
    do_something_with(out)  # do what you want with it 
3

你可以一行一次讀它:

from subprocess import Popen, PIPE 

p = Popen('grep -ir graph .', stdout=PIPE) 
while not p.returncode: 
    s = p.stdout.readline() 
    print s 
    p.poll() 

這樣,您只能處理輸出單行所需的時間。

+0

由於您沒有指定緩衝區大小,因此兩個進程之間會添加4KB緩衝區,所以它們通常不會相互阻塞。 –

-1

您可以使用「tee」命令。它完全符合你的需求。
http://www.computerhope.com/unix/utee.htm

+0

是的,但我需要在Python中處理緩衝區,以瞭解是否應該再次啓動任務。 – Geo

+0

OP在詢問有關從Python代碼中使用popen監控它們啓動的進程的問題,因此這沒有幫助。 – cowbert

相關問題