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

时间:2010-01-21 19:58:18

标签: python google-app-engine

我正在Google Application Engine环境中工作,我从字符串加载doctests和python代码来测试Python家庭作业。我的基本实现(Provided by 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)

2 个答案:

答案 0 :(得分:5)

我认为Hooked has the right answer,但我认为您最好在修改sys.stdout之前存储sys.__stdout__的值,然后在恢复 值而不是恢复{{ 1}}因为(我认为)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

答案 1 :(得分: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__

恢复正常的打印功能。