How do I run a python file that is read into a std::string using PyRun
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 std::string but am now having troubles running it. PyRun_SimpleFileEx didn't seem to do the trick either so some help would be great!
std::string content;
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());
write_line("Script dir: " + script_directory);
////-python_script H:\\CRAW\\craw\\script\\craw.py
//content.c_str()
//FILE *fp;
//fp = fopen("H:\\CRAW\\craw\\script\\craw.py", "r");
//PyRun_SimpleFileEx(fp,开发者_JAVA技巧 "craw.py", 1);
if(PyRun_SimpleString(content.c_str()) != 0)
{
write_line("The main Python script contained errors.");
return false;
}
//PyRun_SimpleString(("execfile('" + ail::replace_string(python_script, "\\", "\\\\") + "')").c_str());
return true;
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;
精彩评论