如何从Python函数调用中捕获标准输出? [英] How to capture stdout output from a Python function call?
问题描述
我正在使用对对象做某事的Python库
I'm using a Python library that does something to an object
do_something(my_object)
并进行更改。这样做时,它会向stdout打印一些统计信息,我希望掌握这些信息。正确的解决方案是更改 do_something()
以返回相关信息,
and changes it. While doing so, it prints some statistics to stdout, and I'd like to get a grip on this information. The proper solution would be to change do_something()
to return the relevant information,
out = do_something(my_object)
,但是<$的开发者还需要一段时间c $ c> do_something()解决此问题。作为一种解决方法,我考虑过解析任何 do_something()
写到stdout的内容。
but it will be a while before the devs of do_something()
get to this issue. As a workaround, I thought about parsing whatever do_something()
writes to stdout.
如何捕获stdout输出在代码的两点之间,例如
How can I capture stdout output between two points in the code, e.g.,
start_capturing()
do_something(my_object)
out = end_capturing()
?
推荐答案
尝试使用此上下文管理器:
Try this context manager:
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
is now a list containing the lines printed by the function call.
高级用法:
可能不明显的是,此操作可以执行多次,并且将结果连接在一起:
What may not be obvious is that this can be done more than once and the results concatenated:
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']
更新:他们在 contextlib
以及 redirect_stderr()
)。因此,您可以使用 io.StringIO
来达到类似的结果(尽管 Captureing
是一个列表以及一个上下文管理器可以说更方便)。
Update: They added redirect_stdout()
to contextlib
in Python 3.4 (along with redirect_stderr()
). So you could use io.StringIO
with that to achieve a similar result (though Capturing
being a list as well as a context manager is arguably more convenient).
这篇关于如何从Python函数调用中捕获标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!