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

标签 python function printing stdout

<分区>

Possible Duplicate:
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 或其他方式打开?

最佳答案

对于 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 的性能可能稍好一些。

关于python - 如何在 python 中重定向函数的打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14197009/

相关文章:

python - 使用 PIL 查找图像中透明区域的位置

python - 将值添加到行并将其复制到 pandas 中该值的正下方

oracle - PL/SQL : Retrieve names of procedures and functions within a package

function - 在模块中包含的函数中添加类型

cocoa - 打印Webview ==更改scaleUnitSquareToSize后剪切的内容

eclipse - 在 Eclipse 上链接 .so 文件

python - 在 Python 3 的一行中打印一个序列

python - Python3-ModuleNotFoundError : No module named 'numpy'

javascript - 如何检查 JavaScript 函数是否返回 Promise?

css - 在新行打印 CSS URL