PYTHONPATH and embedding python

Ken Seehof kseehof at neuralintegrator.com
Wed Oct 10 02:34:59 EDT 2001


> On Tue, 9 Oct 2001, Idriz SMAILI wrote:
>
> > I have the following problem:
> >
> > I have embedded Python in an C++ application. The Python modules are
> > after freezing integrated in the application and those modules should be
> > imported as frozen modules. Before I initialize the Python interpreter
> > I've used the putenv in C code to set the environment variable
> > PYTHONPATH to "pwd == .". I've used the getenv function to check if the
> > environment variable has been changed and it is as expected really
> > changed to the new setting result. The problem is that the Python
> > Interpreter during its initialization uses the same getenv function and
> > it gets the old value of the PYTHONPATH value. This is my problem,
> > because I've got a lot of problems in case the user has installed a
> > different python version, because the Python Interpreter tries to import
> > for example the os module, which is different between Python 1.5.2 and
> > Python 2.1.1. I am using Python 2.1.1 and Microsoft Visual Studio V.
> > 6.0. under WinNT operating system.
> >
> > Does anyone have any suggestions?  Thanks.
>
> Use this bit of code right after Py_Initialize():
>
> ---
>   char *path, *newpath;
>
>   path=Py_GetPath();
>   newpath=strcat(path, ":."); // or ";.", possibly
>   PySys_SetPath(newpath);
>   free(newpath);
> ---

Yikes!  That doesn't look quite right to me.

strcat(char *dest, char *src) returns its first argument after concatenating
*src to it.  In your example, path points to static storage returned by
Py_GetPath.  Your code proceeds to concatenate onto it (blasting away at
static memory reserved for the python library), and then frees it (note that
newpath==path at the end) which it doesn't have a right to do.

You probably mean something like this:

// untested code:
  char *path, *newpath;
  path=Py_GetPath();
  newpath=new char[strlen(path)+4];
  strcpy(newpath, path);
  strcat(newpath, ":.");  // ":." for unix, or ";." for windows
  PySys_SetPath(newpath);
  free(newpath);

from the docs:
char* Py_GetPath ()
Return the default module search path; this is computed from the program
name (set by Py_SetProgramName() above) and some environment variables. The
returned string consists of a series of directory names separated by a
platform dependent delimiter character. The delimiter character is ":" on
Unix, ";" on DOS/Windows, and "\n" (the ASCII newline character) on
Macintosh. The returned string points into static storage; the caller should
not modify its value. The value is available to Python code as the list
sys.path, which may be modified to change the future search path for loaded
modules.

Hmm, I can't seem to find any documentation on PySys_SetPath.  I wonder if
it automatically converts the delimiter (":" <=> ";").

- Ken Seehof
kseehof at neuralintegrator.com






More information about the Python-list mailing list