How to reinitialise an embedded Python interpreter?

前端 未结 3 1195
一向
一向 2021-02-04 13:06

I\'m working on embedding Python in our test suite application. The purpose is to use Python to run several tests scripts to collect data and make a report of tests. Multiple te

3条回答
  •  甜味超标
    2021-02-04 13:45

    How about using code.IteractiveInterpreter?

    Something like this should do it:

    #include 
    #include 
    #include 
    
    using namespace boost::python;
    
    std::string GetPythonError()
    {
        PyObject *ptype = NULL, *pvalue = NULL, *ptraceback = NULL;
        PyErr_Fetch(&ptype, &pvalue, &ptraceback);
        std::string message("");
        if(pvalue && PyString_Check(pvalue)) {
            message = PyString_AsString(pvalue);
        }
        return message;
    }
    
    // Must be called after Py_Initialize()
    void RunInterpreter(std::string codeToRun)
    {
        object pymodule = object(handle<>(borrowed(PyImport_AddModule("__main__"))));
        object pynamespace = pymodule.attr("__dict__");
    
        try {
            // Initialize the embedded interpreter
            object result = exec(   "import code\n"
                                    "__myInterpreter = code.InteractiveConsole() \n", 
                                    pynamespace);
            // Run the code
            str pyCode(codeToRun.c_str());
            pynamespace["__myCommand"] = pyCode;
            result = eval("__myInterpreter.push(__myCommand)", pynamespace);
        } catch(error_already_set) {
            throw std::runtime_error(GetPythonError().c_str());
        }
    }
    

提交回复
热议问题