How To catch python stdout in c++ code

前端 未结 3 471
说谎
说谎 2020-11-27 14:45

I have a program which during it\'s run sometimes needs to call python in order to preform some tasks. I need a function that calls python and catches pythons stdout

3条回答
  •  再見小時候
    2020-11-27 15:05

    If I'm reading your question correctly, you want to capture stdout/stderr into a variable within your C++? You can do this by redirecting stdout/stderr into a python variable and then querying this variable into your C++. Please not that I have not done the proper ref counting below:

    #include 
    #include 
    
    int main(int argc, char** argv)
    {
        std::string stdOutErr =
    "import sys\n\
    class CatchOutErr:\n\
        def __init__(self):\n\
            self.value = ''\n\
        def write(self, txt):\n\
            self.value += txt\n\
    catchOutErr = CatchOutErr()\n\
    sys.stdout = catchOutErr\n\
    sys.stderr = catchOutErr\n\
    "; //this is python code to redirect stdouts/stderr
    
        Py_Initialize();
        PyObject *pModule = PyImport_AddModule("__main__"); //create main module
        PyRun_SimpleString(stdOutErr.c_str()); //invoke code to redirect
        PyRun_SimpleString("print(1+1)"); //this is ok stdout
        PyRun_SimpleString("1+a"); //this creates an error
        PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutErr"); //get our catchOutErr created above
        PyErr_Print(); //make python print any errors
    
        PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object
    
        printf("Here's the output:\n %s", PyString_AsString(output)); //it's not in our C++ portion
    
        Py_Finalize();
    
    
        return 0;
    
    }
    

提交回复
热议问题