小编典典

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

all

我正在使用一个对对象执行某些操作的 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()

?


阅读 1366

收藏
2022-09-02

共1个答案

小编典典

试试这个上下文管理器:

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']

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

2022-09-02