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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.