【问题标题】:How can I redirect print output of a function in python [duplicate]如何在python中重定向函数的打印输出[重复]
【发布时间】:2012-12-21 05:52:34
【问题描述】:

可能重复:
Can I redirect the stdout in python into some sort of string buffer?

我在 python 中有一个函数可以将某些内容打印到标准输出

def foo():
    print("some text")

我想将这个函数中正在打印的文本“重定向”到一个变量中,即“包装”这个函数或其他任何东西,以便将文本存储在一个变量中:

text = wrapper(foo)

是否有一种可靠的方法来临时更改 sys.stdout 或将变量打开为 FileObject 或其他方式?

【问题讨论】:

  • 为什么不直接使用自己的打印功能呢?
  • 函数定义给了,函数本身我不能。
  • 我们是否假设您不能修改函数而只是将打印更改为return?并且您希望在函数期间临时修改sys.stdout(即装饰它)以捕获它?
  • 看看副本——它提供了将sys.stdout重定向到StringIO对象的解决方案。
  • Python 2 还是 3?在 3 中,您可以重新定义 print...

标签: python function printing stdout


【解决方案1】:

对于 python3.4+,标准库中有一个上下文管理器。

with contextlib.redirect_stdout(file_like_object):
    ...

这部分答案已更新,但主要适用于仍陷在 python2.x 世界中的人

如果您被旧版本的 python 困住,那么您自己编写这个上下文管理器并不难。关键是您可以将sys.stdout 更新为您想要的任何类似文件的对象(这就是print 写入的内容):

>>> import sys
>>> import StringIO
>>> stdout = sys.stdout  # keep a handle on the real standard output
>>> sys.stdout = StringIO.StringIO() # Choose a file-like object to write to
>>> foo() 
>>> sys.stdout = stdout
>>> foo()
bar

创建一个context manager 以在您进入上下文时将标准输出设置为您想要的任何内容,然后在您__exit__ 上下文时让上下文管理器重置标准输出。

这是一个使用contextlib 创建上下文管理器的简单示例:

import contextlib
import sys

@contextlib.contextmanager
def stdout_redirect(where):
    sys.stdout = where
    try:
        yield where
    finally:
        sys.stdout = sys.__stdout__

def foo():
    print 'bar'

# Examples with StringIO
import StringIO

with stdout_redirect(StringIO.StringIO()) as new_stdout:
    foo()

new_stdout.seek(0)
print "data from new_stdout:",new_stdout.read()

new_stdout1 = StringIO.StringIO()
with stdout_redirect(new_stdout1):
    foo()

new_stdout1.seek(0)
print "data from new_stdout1:",new_stdout1.read()

# Now with a file object:
with open('new_stdout') as f:
    with stdout_redirect(f):
        foo()

# Just to prove that we actually did put stdout back as we were supposed to
print "Now calling foo without context"
foo()

注意:

在 python3.x 上,StringIO.StringIO 已移动到 io.StringIO。此外,在 python2.x 上,cStringIO.StringIO 的性能可能稍高一些。

【讨论】:

  • +1 表示上下文管理器建议,这可能是最干净的方法。
  • @l4mpi:参见PEP 0343 中的“临时重定向标准输出”。那里还有一些您可能感兴趣的其他示例。
  • 从 Python 3.4 contextlib.redirect_stdout() 也可用。
【解决方案2】:

在 Python 3.x 中,您只需重新定义 print

B = []

def print(str):
    global B
    B.append(str)

def A():
    print("example")

A()

>>> B
['example']

如果出于某种原因,您需要内置打印功能,请执行以下操作:

from builtins import print

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 2020-05-14
    • 1970-01-01
    • 2012-06-22
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多