2013-01-14 62 views
0

我想運行一個外部程序(在這種情況下只是python -V)並捕獲內存中的標準錯誤。如何在Python中捕獲外部進程的輸出

它的工作原理,如果我重定向到磁盤:

import sys, os 
import subprocess 
import tempfile 
err = tempfile.mkstemp() 
print err[1] 
p = subprocess.call([sys.executable, '-V'], stderr=err[0]) 

但是這並不有趣。然後我需要將該文件讀入內存。

我想我可以創建在內存中的東西,會像使用StringIO的一個文件,但這個嘗試失敗:

import sys, os 
import subprocess 
import tempfile 
import StringIO 

err = StringIO.StringIO() 
p = subprocess.call([sys.executable, '-V'], stderr=err) 

我:

AttributeError: StringIO instance has no attribute 'fileno' 

PS。一旦這個工作,我也想捕獲標準輸出,但我想這是一樣的。 ps2。我試圖在Windows和Python 2.7.3

回答

2

以上您需要設置stderr = subprocess.PIPE

如:

p = subprocess.Popen(...,stderr = subprocess.PIPE) 
stdout,stderr = p.communicate() 
#p.stderr.read() could work too. 

,對於這個工作,你需要訪問Popen對象,所以你不能真的在這裏使用subprocess.call(你真的需要subprocess.Popen)。

+0

文檔建議針對:「不要使用標準輸出=管或標準錯誤= PIPE使用此功能。」或者是比你的建議subprocess.PIPE不同? – szabgab

+0

@szabgab - 對不起,我一定是在編輯評論時。你不能在'subprocess.call'中使用'PIPE'(或者至少你不應該)。你可以用'subprocess.Popen'來使用它,就像我在我的答案中已經證明的一樣。 – mgilson

+0

事實上,我以前的評論是在只看到答案的第一行時做出的。子進程.Popen很好地工作。謝謝 – szabgab

0

使用subprocess.check_output。從docs

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) 
Run command with arguments and return its output as a byte string. 
相關問題