【发布时间】:2010-12-03 17:06:20
【问题描述】:
我正在使用 python C++ API 从 C++ 程序运行 python 命令。我想将所有 python 输出捕获到一个字符串,我通过以下重定向进行管理,以捕获 python 的 stdout 和 stderr 输出:
#python script , redirect_python_stdout_stderr.py
class CatchOutput:
def __init__(self):
self.value = ''
def write(self, txt):
self.value += txt
catchOutput = CatchOutput()
sys.stdout = catchOutput
sys.stderr = catchOutput
#C++ code
PyObject *pModule = PyImport_AddModule("__main__");
PyRun_SimpleString("execfile('redirect_python_stdout_stderr.py')");
PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutput");
PyObject *output = PyObject_GetAttrString(catcher,"value");
char* pythonOutput = PyString_AsString(output);
但我不知道该怎么做才能捕获 python 解释器的输出 ....
【问题讨论】:
标签: c++ python redirect python-c-api python-embedding