python - 如何从 Python 函数调用中捕获标准输出输出?

标签 python stdout capture

我正在使用一个对对象执行某些操作的 Python 库

do_something(my_object)

并改变它。这样做时,它会将一些统计信息打印到标准输出,我想掌握这些信息。正确的解决方案是更改 do_something() 以返回相关信息,

out = do_something(my_object)

但是 do_something() 的开发人员还需要一段时间才能解决这个问题。作为一种解决方法,我考虑解析 do_something() 写入标准输出的任何内容。

如何捕获代码中两点之间的标准输出输出,例如,

start_capturing()
do_something(my_object)
out = end_capturing()

?

最佳答案

试试这个上下文管理器:

from io import StringIO 
import sys

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        del self._stringio    # free up some memory
        sys.stdout = self._stdout

用法:

with Capturing() as output:
    do_something(my_object)

output 现在是一个列表,其中包含函数调用打印的行。

高级用法:

可能不明显的是,这可以多次执行并且结果连接起来:

with Capturing() as output:
    print('hello world')

print('displays on screen')

with Capturing(output) as output:  # note the constructor argument
    print('hello world2')

print('done')
print('output:', output)

输出:

displays on screen                     
done                                   
output: ['hello world', 'hello world2']

更新:他们将 redirect_stdout() 添加到 contextlib在 Python 3.4 中(连同 redirect_stderr())。因此,您可以使用 io.StringIO 来实现类似的结果(尽管 Capturing 作为列表和上下文管理器可以说更方便)。

关于python - 如何从 Python 函数调用中捕获标准输出输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16571150/

相关文章:

bash - bash 是否可以通过 stdin/stdout 交替读取和写入子进程 "interactively"?

android - 屏幕截图代码Android的任何屏幕

html - 检测 HTML5 Media Capture API 支持

C++ 控制台 "Screen capture"问题

python - 如何从 Python 接口(interface)调试底层 C++ 库?

python - 用于在 Unicode 字符串的嵌套字典中将所有键和值强制为小写的优雅的 pythonic 解决方案?

python - 静态文件的 Google App Engine 自定义 404 页面

python - 如何模拟掷骰子

linux - dup2 vs close+open 用于 stdout 重定向

TFS,如何从构建后获取输出?