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?
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.
I found cross-platform solution. Before invoke any other python code just execute following python lines:
import sys
sys.path.append("C:\\source\\\\modules")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With