gpt4 book ai didi

python - 如何在 IPython Notebook 中显示扩展模块的日志语句

转载 作者:行者123 更新时间:2023-11-28 18:45:20 25 4
gpt4 key购买 nike

我正在开发一个混合 C++ 和 Python 的模块,通过 Cython 连接。 C++ 代码包括简单的日志记录功能,可将日志语句打印到控制台。通过 Python 或 IPython 命令行使用模块时,日志语句会正确打印。但是,该模块主要用于 IPython HTML Notebook。在笔记本中,不会出现日志语句。我该如何解决这个问题?

最佳答案

您可以通过使用 ctypes 库并 Hook libc stdout 文件描述符来实现:http://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/

我已经用 cython 测试过了,它工作正常。

在这里为后代复制 python3 代码:

from contextlib import contextmanager
import ctypes
import io
import os, sys
import tempfile

libc = ctypes.CDLL(None)
c_stdout = ctypes.c_void_p.in_dll(libc, 'stdout')

@contextmanager
def stdout_redirector(stream):
# The original fd stdout points to. Usually 1 on POSIX systems.
original_stdout_fd = sys.stdout.fileno()

def _redirect_stdout(to_fd):
"""Redirect stdout to the given file descriptor."""
# Flush the C-level buffer stdout
libc.fflush(c_stdout)
# Flush and close sys.stdout - also closes the file descriptor (fd)
sys.stdout.close()
# Make original_stdout_fd point to the same file as to_fd
os.dup2(to_fd, original_stdout_fd)
# Create a new sys.stdout that points to the redirected fd
sys.stdout = io.TextIOWrapper(os.fdopen(original_stdout_fd, 'wb'))

# Save a copy of the original stdout fd in saved_stdout_fd
saved_stdout_fd = os.dup(original_stdout_fd)
try:
# Create a temporary file and redirect stdout to it
tfile = tempfile.TemporaryFile(mode='w+b')
_redirect_stdout(tfile.fileno())
# Yield to caller, then redirect stdout back to the saved fd
yield
_redirect_stdout(saved_stdout_fd)
# Copy contents of temporary file to the given stream
tfile.flush()
tfile.seek(0, io.SEEK_SET)
stream.write(tfile.read())
finally:
tfile.close()
os.close(saved_stdout_fd)

在你的代码中:

f = io.BytesIO()

with stdout_redirector(f):
print('foobar')
print(12)
libc.puts(b'this comes from C')
os.system('echo and this is from echo')
print('Got stdout: "{0}"'.format(f.getvalue().decode('utf-8')))

关于python - 如何在 IPython Notebook 中显示扩展模块的日志语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21284817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com