embedded python pythonpath

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 25 19:21:15 EDT 2008


Furkan Kuru <furkankuru <at> gmail.com> writes:

> I've tried below code (Setting pythonpath environment variable)
> and then initialize python interpreter but the embedded python interpreter 
did not get the newly assigned PYTHONPATH. 
> I ve looked at the sys.path in python code (that is run by the embedded 
interpreter) and it behaved according to older pythonpath.

Note that you don't HAVE to set the environment variable PYTHONPATH, there are 
other ways to get directories listed in sys.path - and that is what really 
counts.
The simplest way is to just write code to insert the desired directories in 
front of sys.path, after the call to Py_Initialize. The only problem is that 
some modules (like site and sitecustomize) are searched and executed before 
your code has a chance to modify sys.path - I hope it's not a problem for you.

> Setting environment variable seemed to be correct. 
> Does py_initialize run in another thread so it starts before setting the 
environment var?

I could reproduce the problem with a smaller code (using C, not C++). Testing 
with Python 2.5.1 doesn't work (that means, it ignores the new setting for 
PYTHONPATH). Testing with current Python trunk (from svn) *does* work. I don't 
know if this is a bug that has been fixed, or it works that way because the 
svn version is not the default installation and then searches for things in a 
different way.

#include <Python.h>

int main(int argc, char *argv[])
{
  putenv("PYTHONPATH=C:\\TEMP\\MF");
  system("set PYTHONPATH");
  printf("Py_GETENV(PYTHONPATH)=%s\n", Py_GETENV("PYTHONPATH"));

  Py_Initialize();
  PyRun_SimpleString("import sys\nprint sys.path");
  Py_Finalize();
  return 0;
}

I compiled twice with these commands:
cl -MD -Ic:\apps\python25\include test.c c:\apps\python25
\Libs\Python25.lib /Fetest25.exe
cl -MD -Ic:\apps\python\trunk\PC -Ic:\apps\python\trunk\include test.c 
c:\apps\python\trunk\PCbuild\Python26.lib /Fetest26.exe

Python25.dll and Python26.dll both were copied into the current directory.

test25.exe:
PYTHONPATH=C:\TEMP\MF
Py_GETENV(PYTHONPATH)=C:\TEMP\MF
['C:\\Apps\\Python25\\lib\\site-packages\\setuptools-0.6c5-
py2.5.egg', 'C:\\Apps\\Python25\\lib\\site-packages\\
simplejson-1.7.1-py2.5-win32.egg', 
... many directories, not including C:\TEMP\MF ... ]

test26.exe:
PYTHONPATH=C:\TEMP\MF
Py_GETENV(PYTHONPATH)=C:\TEMP\MF
'import site' failed; use -v for traceback
['C:\\TEMP\\MF', 'C:\\TEMP\\python26.zip', '', 'C:\\TEMP']

I don't understand how the test program, compiled for 2.5.1, could actually 
locate the Python directory. (It's not in my PATH, it's not the default 
install directory, and I deleted the HKLM\Software\Python\PythonCore\2.5 
registry key).

-- 
Gabriel Genellina





More information about the Python-list mailing list