2010-01-21 70 views
0

我正在Google應用程序引擎環境中工作,我正在從字符串加載doctests和python代碼來測試Python作業分配。我的基本實現(Provided by Alex Martelli)似乎適用於我所有的問題,除了那些包含print語句的問題。當我嘗試在GAE中執行打印命令時,某些東西似乎出錯了。在Google App Engine中的Python中,如何捕獲由print語句生成的輸出?

你會如何修改這個例子來捕獲由print語句寫出的任何東西?

#This and most other code works 
class X(object): pass 

x=X() 
exec 'a=23' in vars(x) 


#This throws an error. 
class X(object): pass 

x=X() 
exec 'print 23' in vars(x) 
+3

...使用日誌模塊代替,不是嗎? – jldupont 2010-01-21 20:12:27

+0

它拋出了什麼錯誤? – 2010-01-21 21:48:28

回答

5

我覺得Hooked has the right answer,但我認爲你會更好存儲sys.stdout值之前對其進行修改和事後恢復價值,而不是恢復sys.__stdout__因爲(我認爲)在App Engine運行時與sys.stdout在修補匠它自己的方式。

說的是你喜歡的東西

import StringIO 
import sys 

# Store App Engine's modified stdout so we can restore it later 
gae_stdout = sys.stdout 

# Redirect stdout to a StringIO object 
new_stdout = StringIO.StringIO() 
sys.stdout = new_stdout 

# Run your code here, however you're doing that 

# Get whatever was printed to stdout using the `print` statement (if necessary) 
printed = new_stdout.getvalue() 

# Restore App Engine's original stdout 
sys.stdout = gae_stdout 
4

對於這個問題,我喜歡直接捕獲字符串輸出。裏面的功能我會使用類似:

import StringIO, sys 

# create file-like string to capture output 
codeOut = StringIO.StringIO() 

# capture output and errors 
sys.stdout = codeOut 
err = '' 

try : 
    exec code in code_namespace 
except Exception: 
    err = str(sys.exc_info()[1]) 

,並完成和:
# restore stdout and stderr
sys.stdout = sys.__stdout__

要恢復打印功能正常。

相關問題