Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to modify PYTHONPATH at runtime?

I have a C++ application dynamically linked to the Python interpreter. I want to be able to import python modules from a particular directory. I want to modify the PYTHONPATH for my process so that sys.path will include the paths that I added to the PYTHONPATH. That seems to be the way it works according to this documentation:

http://docs.python.org/c-api/intro.html#embedding-python

However, when I print sys.path from Python-land it has the original contents of PYTHONPATH and not the one I set. Here's an example of what I'm doing (using Boost.Python):

int main(int argc, char* argv[])
{
  _putenv_s("PYTHONPATH", "C:\\source\\\\modules");
  Py_Initialize();
  object main = import("__main__");
  object global = (main.attr("__dict__"));
  exec("import sys\nprint sys.path"), global, global);
}

PS - I know there are other ways to accomplish my goal, but that's not what I'm asking about. I am wondering why Py_Initialize() doesn't use the current value of PYTHONPATH when setting up sys.path. Or perhaps I've misunderstood how it is supposed to work?

like image 248
Skrymsli Avatar asked Mar 15 '11 21:03

Skrymsli


People also ask

Can Pythonpath have multiple paths?

The value of PYTHONPATH can contain multiple locations separated by os.pathsep : a semicolon ( ; ) on Windows and a colon ( : ) on Linux/macOS. Invalid paths are ignored.


1 Answers

I found cross-platform solution. Before invoke any other python code just execute following python lines:

import sys
sys.path.append("C:\\source\\\\modules")
like image 159
Dewfy Avatar answered Oct 06 '22 21:10

Dewfy