Python 如何将函数中的所有打印结果放入变量中?

Python 如何将函数中的所有打印结果放入变量中?,python,python-2.7,printing,io-redirection,Python,Python 2.7,Printing,Io Redirection,我在Python中有一个函数: def f(): ... a lot of code ... print "hello" ... a lot of code ... 我想调用这个函数,但是,打印结果将被放入一个变量中,而不是直接在屏幕上打印。如何使用Python实现这一点? 附言: 请不要只是返回,有时我不知道print语句在哪里。假设print正在写入sys.stdout,您可以临时用类似StringIO对象的内容替换它 stdout

我在Python中有一个函数:

def f():
    ...
    a lot of code
    ...
    print "hello"
    ...
    a lot of code
    ...
我想调用这个函数,但是,打印结果将被放入一个变量中,而不是直接在屏幕上打印。如何使用Python实现这一点? 附言:
请不要只是返回,有时我不知道print语句在哪里。

假设
print
正在写入
sys.stdout
,您可以临时用类似
StringIO
对象的内容替换它

stdout = sys.stdout
sys.stdout = StringIO()
f()
x = sys.stdout.getvalue()
sys.stdout = stdout
或者,如果您有一个对
print
正在使用的文件句柄的引用,您可以使用它而不是
sys.stdout

如果从
f
内部可以多次使用
print
,而您只想捕获其中的一部分(例如,仅从
f
内部调用的函数
g
),恐怕您运气不好。您需要进行的内省量将使您能够简单地重新实现函数,以在变量中累积所需的输出,而不是使用
print

def f():
    #code
    variable = 'hello\n'
    #code
    variable += 'hello2\n'
    #code
    ...

    print(variable)

然后

print(f())

使用下面这样的装饰器

import sys
from StringIO import StringIO
s = StringIO()


def catch_stdout(user_method):
    sys.stdout = s
    def decorated(*args, **kwargs):
        user_method(*args, **kwargs)
        sys.stdout = sys.__stdout__
        print 'printing result of all prints in one go'
        s.seek(0, 0)
        print s.read()
    return decorated


@catch_stdout
def test():
    print 'hello '
    print 'world '


test()

如果您发现需要经常这样做,也可以定义自己的上下文管理器,以便捕获语句块的输出,例如:

import contextlib
from StringIO import StringIO
import sys

@contextlib.contextmanager
def capture_stdout():
    old_stdout = sys.stdout
    sys.stdout = StringIO()
    yield sys.stdout, old_stdout
    sys.stdout = old_stdout
然后按如下方式使用:

def something():
    print 'this is something'

# All prints that go to stdout inside this block either called
# directly or indirectly will be put into a StringIO object instead
# unless the original stdout is used directly...
with capture_print() as (res, stdout):
    print 'hello',
    print >> stdout, "I'm the original stdout!" 
    something()

print res.getvalue() + 'blah' # normal print to stdout outside with block
给你:

I'm the original stdout
hello this is something
blah

我不知道print语句在哪里,因为我调用了这个函数中的其他函数。我不理解否决票,这不是一个完全合理的问题吗?我想这是因为你的问题不清楚。通常,最好提供一份报告,以便人们能够重现您的问题。另外,有些人会因为没有解释就投反对票。我觉得这毫无帮助。
I'm the original stdout
hello this is something
blah