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

时间:2016-08-14 15:30:54

标签: python python-2.7 printing io-redirection

我在Python中有一个函数:

def f():
    ...
    a lot of code
    ...
    print "hello"
    ...
    a lot of code
    ...

我想调用此函数,但是,打印结果将被放入变量而不是直接在屏幕上打印。我怎么能用Python做到这一点? PS: 请不要只返回,有时我不知道打印声明在哪里。

4 个答案:

答案 0 :(得分:3)

假设print正在写sys.stdout,您可以暂时将其替换为StringIO对象。

stdout = sys.stdout
sys.stdout = StringIO()
f()
x = sys.stdout.getvalue()
sys.stdout = stdout

或者,如果您对print正在使用的文件句柄有引用,则可以使用该句柄代替sys.stdout

如果print内有f的多种用途,您只想捕获其中的部分(例如,仅来自函数gf内部打来的电话,我担心你运气不好。您需要做的内省量可以让您简单地重新实现该函数,以便在变量中累积所需的输出,而不是使用print

答案 1 :(得分:1)

使用下面的装饰

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()

答案 2 :(得分:1)

如果您发现需要执行此操作,也可以定义自己的上下文管理器,以便捕获语句块的输出,例如:

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

答案 3 :(得分:-1)

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

    print(variable)

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

    return(variable)

然后

print(f())