跳转到主要内容

在上下文管理器中捕获C级别输出

项目描述

怀尔德利兹

通过os.dup2在Python中捕获C级别的stdout/stderr管道。

有关为何需要此功能的更多详细信息,请参阅此博客文章

安装

pip install wurlitzer

使用方法

在管道中捕获stdout/stderr

from wurlitzer import pipes

with pipes() as (out, err):
    call_some_c_function()

stdout = out.read()

在单个StringIO对象中捕获stdout和stderr

from io import StringIO
from wurlitzer import pipes, STDOUT

out = StringIO()
with pipes(stdout=out, stderr=STDOUT):
    call_some_c_function()

stdout = out.getvalue()

将C级别的stdout/stderr转发到Python sys.stdout/syserr,它可能已被环境转发到某处,例如IPython

from wurlitzer import sys_pipes

with sys_pipes():
    call_some_c_function()

将C级别的输出转发到Python Logger对象(3.1版新功能)。每行输出将是一条日志消息。

from wurlitzer import pipes, STDOUT
import logging

logger = logging.getLogger("my.log")
logger.setLevel(logging.INFO)
logger.addHandler(logging.FileHandler("mycode.log"))

with pipes(logger, stderr=STDOUT):
    call_some_c_function()

将C级别的输出转发到文件(避免了与后台线程的GIL问题,3.1版新功能)

from wurlitzer import pipes, STDOUT

with open("log.txt", "ab") as f, pipes(f, stderr=STDOUT):
    blocking_gil_holding_function()

或者更简单,将其作为IPython扩展启用

%load_ext wurlitzer

在执行期间将所有C级别的输出转发到IPython(例如Jupyter单元格输出)。

致谢

本软件包基于我们在为Jupyter的Cling内核捕获输出时,与@takluyver和@karies合作所学到的知识。

怀尔德利兹?!

怀尔德利兹制造管风琴。懂了吗?管风琴?命名太难了。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

wurlitzer-3.1.1.tar.gz (11.9 kB 查看哈希值)

上传时间

构建分发

wurlitzer-3.1.1-py3-none-any.whl (8.6 kB 查看哈希值)

上传时间 Python 3