【问题标题】:In Python in Google App Engine, how do you capture output produced by the print statement?在 Google App Engine 中的 Python 中,如何捕获 print 语句产生的输出?
【发布时间】:2010-01-21 19:58:17
【问题描述】:

我在 Google 应用程序引擎环境中工作,我从字符串中加载 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)

【问题讨论】:

  • ...改用日志模块,不是吗?

标签: python google-app-engine


【解决方案1】:

我认为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

【讨论】:

    【解决方案2】:

    对于这个问题,我喜欢直接捕获字符串输出。在你的函数中,我会使用类似的东西:

    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__

    恢复正常的打印功能。

    【讨论】:

      猜你喜欢
      • 2013-01-25
      • 1970-01-01
      • 2023-03-23
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多