试试这个上下文管理器:
from io import StringIO import sysclass 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()到
contextlibPython
3.4中(以及
redirect_stderr())。因此,您可以使用
io.StringIO它来达到类似的结果(尽管
Capturing列表和上下文管理器可能更方便)。



