如何在python中重定向函数的打印输出

时间:2013-01-07 13:31:06

标签: python function printing stdout

  

可能重复:
  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或其他内容?

2 个答案:

答案 0 :(得分:18)

对于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以在输入上下文时将stdout设置为您想要的任何内容,然后让上下文管理器在您__exit__上下文时重置stdout。

以下是使用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 :(得分:7)

在Python 3.x中,您可以重新定义print

B = []

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

def A():
    print("example")

A()

>>> B
['example']

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

from builtins import print