How to redirect python interpreter output and intercept it in a line in a C ++ program?

I am using the python C ++ API to run python commands from a C ++ program. I want to catch all python output in a string, I succeeded using the following redirection to catch python output stdout and 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);

But I don’t know what to do to catch the output of the python interpreter ....

+3
source share
1 answer

Python ++-, stderr stdout ++. , . , Python script - stdout ++.

+4

Source: https://habr.com/ru/post/1778355/


All Articles