2011-03-23 18 views
1

這裏有事情,我試圖做的:蟒蛇 - 捕捉與它們的殼子進程的標準錯誤標準輸出活着

 
-python process captures stderr of multiple subprocesses to watch the subprocesses 
-each subprocess runs on the separate window displaying stdout. 

當我使用POPEN(命令,標準錯誤= fp4tempfile

 
(good) the python process can capture stderr of the subprocesses 
(bad) the subprocess shells stop displaying stdout. 

當我使用POPEN(命令

 
(good) each subprocess shells displays stdout (as well as stderr, which does not matter for me), 
(bad) the python process cannot capture stderr. 

我想既「好」。我能爲此做些什麼?提前致謝。 (目前,我使用python3.2在Windows7開發)

這裏是用Python編寫的父進程來源:

import os,subprocess 
import time 
fpws = [] 
fprs = [] 

def run_command(command): 
    <specifying a file to write -- skipped> 
    fpw = open(ftempname,'w') 
    fpr = open(ftempname,'r') 
    #cmd_redirect = "%s 2>%s" % (command,ftempname)#didnt do anything 
    #starting a sub-program: 
    pp = subprocess.Popen(command,stderr = fpw) #++ 
    #pp = subprocess.Popen(command)    #@@ 
    fpws.append(fpw) 
    fprs.append(fpr)  

def watch_program(): 
    while True: #running forever for simplfication 
     for fpr in fprs: 
      outchunk = fpr.read() 
      <do something for subprocesses stderr -- skipped> 
      time.sleep(1.0) 

if __name__ == '__main__': 
    cmd1 = '(path to program1)' 
    cmd2 = '(path to program2)' 
    run_command(cmd1) #kicking cmd1 
    run_command(cmd2) #kicking cmd2 
    watch_program()   #hearing stderr msg from the other process 

注:在子側,fflush(標準輸出)和fflush(錯誤)根據需要調用。

回答

0

沒有測試過這一點,但你可以做

import sys 

pp = subprocess.Popen(command, stderr = fpw, stdout = sys.stdout) 
+0

編輯:沒有注意到子進程是在不同的窗口。不知道爲什麼更改stderr會對輸出到stdout的內容產生任何影響。你確定輸出消失的原因是它實際上是錯誤的嗎? – I82Much 2011-03-24 15:50:43

0

I82Much,謝謝你的回答和評論。

是的,您對stderr的評論是完全正確的。我在windows7中開發。在Linux操作系統(ubuntu10),下面簡單地計算出:

 
    cmd_line4sub = command + ' 2> ' + ftempname 
    pp = subprocess.Popen(['/usr/bin/xterm','-e',cmd_line4sub],stderr = fpw) 

它打開新的彈,印刷子標準輸出。父進程捕獲子進程stderr。這是我的第一個目標。

如果我所能想出如何在Windows中執行,我會後我的答案;)

(我是同一個用戶的提問,但我不能讓他們在同一帳戶... )

相關問題