在Google App Engine的Python中,如何捕获print语句产生的输出?

Chr*_*ris 0 python google-app-engine

我正在Google Application Engine环境中工作,我从字符串加载doctests和python代码来测试Python家庭作业.我的基本实现(由Alex Martelli提供)似乎适用于我的所有问题,除了那些包含print语句的问题.当我尝试在GAE中执行打印命令时,似乎出现了问题.

您如何修改此示例以捕获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)
Run Code Online (Sandbox Code Playgroud)

Wil*_*hen 5

我认为Hooked有正确的答案,但我认为你最好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
Run Code Online (Sandbox Code Playgroud)