0

Within a larger class I have a section of code for importing a python script and running it. The file (animate.py) is contained within the same directory as the executable.

void classname::show( void )
{
         stringstream run_cmd;
         run_cmd << "animate.run('" << name << "')";

         Py_Initialize();
         PyRun_SimpleString("import animate");
         PyRun_SimpleString(run_cmd.str().c_str());
         Py_Finalize();
}

The thing is, I'm working through two computers, when compiled on one of these, this works fine. On my personal laptop it fails to import the scipt with the error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named animate
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'animate' is not defined

They're both compiled through the exact same makefile, with the -lpython2.7 flag used. The file structure is also the same.

Is there some library I'm missing to do this?

1 Answer 1

1

You need to add the current working directory to Python path (it's not included by default):

     Py_Initialize();
     PyObject *sys_path = PySys_GetObject("path");
     PyList_Append(sys_path, PyString_FromString("."));
     PyRun_SimpleString("import animate");
     PyRun_SimpleString(run_cmd.str().c_str());
     Py_Finalize();
Sign up to request clarification or add additional context in comments.

2 Comments

That certainly works for being able to import the script, but now that script can't import numpy etc. Do I have to set a path for that as well?
Also I'm still curious why this works on the other machine fine without setting the path, but not on this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.