我如何可以重定向Python中的函数的打印输出[复制]我如何可以重定向Python中的函数的打印输出

2019-05-12 08:01发布

可能重复:
我也可以把在python标准输出成某种字符串缓冲区?

我有蟒蛇的功能,打印的东西到标准输出

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

我想“重定向”正在打印在这个函数转换成一个变量,即“包装”这个函数或任何使得文本存储在变量中的文本:

text = wrapper(foo)

有没有一种可靠的方法来暂时改变sys.stdout或打开一个变量作为一个FileObject ,还是其他什么东西?

Answer 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

要创建一个上下文管理到标准输出设置成任何你想要的,当你进入情境,然后有上下文管理器复位标准输出,当你__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可能会稍微更好的性能。



Answer 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


文章来源: How can I redirect print output of a function in python [duplicate]