[英]Redirection of stdout from a SWIG-wrapped C++ class to a non-file python object
我正在尝试将SWIG包装的C模块的输出重定向到python类。 SWIG调用程序是一个python类,该类已经通过以下方式覆盖了sys.stdout:
with _redirect_streams():
my_C_function(sys.stdout)
try:
out_s = sys.stdout.getvalue()
except AttributeError:
out_s = ""
try:
err_s = sys.stderr.getvalue()
except AttributeError:
err_s = ""
class _redirect_streams(object):
def __enter__(self):
self._orig_stdout = sys.stdout
self._orig_stderr = sys.stderr
sys.stdout = StringIO()
sys.stderr = StringIO()
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self._orig_stdout
sys.stderr = self._orig_stderr
在SWIG中,我能够将所有printf重定向到我从python传递的文件句柄FILE* fh
。
如果我调用传递sys.__stdout__
(实际文件对象)的C函数,它会很好地工作,但是如果我在覆盖sys.stdout
之后传递sys.stdout
,则它不再是python文件对象(StringIO),并且C文件无法打印到该文件。 。
在那种情况下最好的方法是什么?
有没有办法在仍将文件类型句柄传递给C函数的同时捕获python中的标准输出?
编辑:实际上,我稍微简化了一点,在我的代码中, my_C_function
仍然是一个python函数,它在调用SWIG-wrapper C函数时将其输出到stdout上,该函数本身会打印到给定的文件句柄。
谢谢,Herve
我只能为您提供一种方法。
1.使用os.pipe()创建一个fd对2.将“ write”管道向下传递到C 3.使用该管道覆盖“ stdout”(在C-land中)4.现在,“ C” stdout将用于出现在该os.pipe()的“读取”侧。5.返回python-land,从管道中读取并写入Python的stdout。
...可能有一种更简单的方法...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.