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

I'm using a Python library that does something to an object

do_something(my_object)

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)

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.

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

Usage:

with Capturing() as output:

do_something(my_object)

output is now a list containing the lines printed by the function call.

Advanced usage:

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)

Output:

displays on screen

done

output: ['hello world', 'hello world2']

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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值