Is it possible to modify PYTHONPATH at runtime?

Skrymsli picture Skrymsli · Mar 15, 2011 · Viewed 9.3k times · Source

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?

Answer

Dewfy picture Dewfy · Nov 18, 2011

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

import sys
sys.path.append("C:\\source\\\\modules")