在Google App Engine中的Python中,如何捕获print语句产生的输出? [英] In Python in Google App Engine, how do you capture output produced by the print statement?

查看:129
本文介绍了在Google App Engine中的Python中,如何捕获print语句产生的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Google Application Engine环境中工作,在该环境中,我从字符串加载doctests和python代码以测试Python作业分配.我的基本实现(

I am working in the Google Application Engine environment where I am loading doctests and python code from strings to test Python homework assignments. My basic implementation (Provided by Alex Martelli) appears to work for all of my problems except for those containing the print statement. Something seems to go wrong when I attempt to execute the print command within GAE.

您将如何修改此示例以捕获print语句写出的所有内容?

How would you modify this example to capture anything written out by the print statement?

#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)

推荐答案

我认为

I think Hooked has the right answer, but I think you'd be better off storing the value of sys.stdout before you modify it and restoring that value afterwards rather than restoring sys.__stdout__ because (I think) the App Engine runtime tinkers with sys.stdout in its own way.

这给你留下了类似的东西

That leaves you with something like

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

这篇关于在Google App Engine中的Python中,如何捕获print语句产生的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆