2013-01-16 57 views
0

使用subprocess.Popen時遇到了問題。我經歷了這個問題here。當我添加了以下編輯到fake_utility.py即添加標準錯誤= subprocess.PIPE在subprocess.Popen讀取子進程的STDERR

#fake_utility.py 
import time 
i = 0 
while True: 
    print hex(i)*512 
    i += 1 
    time.sleep(0.5) 

#python interpreter 
import subprocess 
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
for err in proc.stderr: 
    print "err::", err 

for line in proc.stdout: 
    print "test:", line.rstrip() 

程序犯規響應。當我按Ctrl-C時,我得到以下內容:

Traceback (most recent call last): 
File "run_fake_utility.py", line 6, in <module> 
    err = proc.stderr.readline() 
KeyboardInterrupt 

它在proc.stderr.readline()中被阻止。如果我從proc.stderr中刪除行讀取,程序運行良好。

可能的錯誤是什麼?我正在使用Python2.6。

回答

1

從STDERR讀取時阻塞會表明子進程沒有向該文件句柄寫入任何內容。

你真的期待什麼嗎? (即:如果從shell手動運行相同的命令和重定向STDERR - 2>file.txt - 到一個文件,是文件非空?)

否則,會出現一些共同的東西:

  • 您還沒有收到一個換行符在STDERR輸出
  • 您還沒有收到足夠的數據來填補一些潛在的緩衝區
+0

我只是想,如果任何打印出的錯誤。我從shell手動運行命令,將STDERR重定向到文件,並且它是空的。 – ashokadhikari

+0

然後這意味着,如果STDERR輸出中沒有任何內容,那麼程序將永遠阻塞。應該做些什麼來避免這種情況? – ashokadhikari

+0

@ liken.one使用[select](http://docs.python.org/2/library/select.html)或[threads](http://docs.python.org/2/library/threading)和在一定時間內殺死線程。 – cyraxjoe