栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

试试这个上下文管理器:

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611040.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号