How do I run a python file that is read into a std::string using PyRun

前端 未结 1 1994
时光取名叫无心
时光取名叫无心 2021-01-27 19:57

I am embedding Python into my C++ program, and have used PyRun_SimpleString quite effectively but now am having trouble.

What I have done is loaded a python.py file a st

相关标签:
1条回答
  • 2021-01-27 20:09

    I solved my problem by using a string vector and reading each line of the file into the vector, then executing each one using PyRun_SimpleString.

    Here's the finished code, no error checking though. std::vector string_vector; std::string content; if(python_script.empty()) return true;

        ail::read_lines(python_script, string_vector);
    
        if(!ail::read_file(python_script, content))
        {
            error("Failed to load Python script \"" + python_script + "\"");
            return false;
        }
    
        if(prompt_mode)
            initialise_console();
    
        content = ail::replace_string(content, "\r", "");
    
        Py_Initialize();
        initialise_module();
    
        std::string script_directory;
        if(get_base_name(python_script, script_directory))
            PyRun_SimpleString(("import sys\nsys.path.append('" + script_directory + "')\n").c_str());
    
        for(int i = 0; i < string_vector.size(); i++)
        {
            string_vector[i] = ail::replace_string(string_vector[i], "\r", "");
            PyRun_SimpleString(string_vector[i].c_str());
        }
    
        return true;
    
    0 讨论(0)
提交回复
热议问题