如果我正确地阅读了您的问题,您想将stdout / stderr捕获到C 中的变量中吗?您可以通过将stdout /
stderr重定向到python变量,然后将此变量查询到C 中来实现。请不要说我没有在下面做适当的引用计数:
#include <Python.h>#include <string>int main(int argc, char** argv){ std::string stdOutErr ="import sysnclass CatchOutErr:n def __init__(self):n self.value = ''n def write(self, txt):n self.value += txtncatchOutErr = CatchOutErr()nsys.stdout = catchOutErrnsys.stderr = catchOutErrn"; //this is python pre to redirect stdouts/stderr Py_Initialize(); PyObject *pModule = Pyimport_AddModule("__main__"); //create main module PyRun_SimpleString(stdOutErr.c_str()); //invoke pre 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;}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)