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