在上下文管理器中捕获c级输出
wurlitzer的Python项目详细描述
沃利泽
通过os.dup2
在python中捕获c级stdout/stderr管道。
有关为什么需要此功能的详细信息,请阅读this blog post。
安装
pip install wurlitzer
用法
在管道中捕获stdout/stderr:
fromwurlitzerimportpipeswithpipes()as(out,err):call_some_c_function()stdout=out.read()
在stringio中捕获stdout/stderr:
fromioimportStringIOfromwurlitzerimportpipes,STDOUTout=StringIO()withpipes(stdout=out,stderr=STDOUT):call_some_c_function()stdout=out.getvalue()
将C级stdout/stderr转发到python sys.stdout/stderr, 可能已经被环境转发到某个地方,例如ipython:
fromwurlitzerimportsys_pipeswithsys_pipes():call_some_c_function()
或者更简单一些,启用它作为ipython扩展:
%load_ext wurlitzer
在执行期间将所有C级输出转发到IPython。
致谢
这个包是基于我们在捕获jupyter的Cling Kernel输出时用@takluyver和@karies学习到的东西。
沃利泽?!
Wurlitzer制造管器官。了解了?管?命名很难。