i am using python C++ API to run python开发者_运维百科 commands from C++ program. I want to catch all the python output to a string, I've managed by the following redirection, to catch pythons stdout and stderr output:
#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);
But i don't know what to do to catch also pythons interpreter output ....
The Python interpreter will run inside your C++ process, so all its output will go to the stderr and stdout of the C++ program itself. How to capture this output is described in this answer. Note that with this approach you won't need to capture the output in the Python script any more -- just let it go to stdout and capture everything at once in C++.
精彩评论