3

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 ....

Amro
  • 123,847
  • 25
  • 243
  • 454
alexpov
  • 1,158
  • 2
  • 16
  • 29

1 Answers1

4

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++.

Community
  • 1
  • 1
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841