如何在C++程序中重定向Python解释器输出并捕获为字符串?
我正在使用Python的C++接口,从C++程序中运行Python命令。我想把所有的Python输出都捕捉到一个字符串里。通过以下的重定向,我已经成功捕捉到了Python的标准输出和错误输出:
#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解释器的输出……
1 个回答
4
Python解释器会在你的C++程序里面运行,所以它产生的所有输出都会直接发送到C++程序的错误输出和标准输出中。如何捕捉这些输出的具体方法可以在这个回答中找到。需要注意的是,使用这种方法后,你就不需要在Python脚本里捕捉输出了——只需让它直接输出到标准输出,然后在C++中一次性捕捉所有内容。