PyImport_ImportModule/embedding: surprising behaviors

Ziga Seilnacht ziga.seilnacht at gmail.com
Sat Mar 24 16:20:36 EDT 2007


David Abrahams wrote:
> I'm seeing highly surprising (and different!) behaviors of
> PyImport_ImportModule on Linux and Windows when used in a program with
> python embedding.
>
> On Linux, when attempting to import a module xxx that's in the current
> directory, I get
>
>   ImportError: No module named xxx
>
> I can work around the problem by setting
>
>   PYTHONPATH=.

Python puts the current directory in sys.path only if it can't
determine the directory of the main script. There was a bug on
Windows that always added current directory to sys.path, but it
was fixed in Python 2.5. This is documented in the library
reference:

http://docs.python.org/lib/module-sys.html#l2h-5149

> On Windows, I get:
>
>   'import site' failed; use -v for traceback
>
> I can work around the problem by setting PYTHONPATH to point to the
> python library directory:
>
>   set PYTHONPATH=c:\Python25\Lib

This happens because Python calculates the initial import path by
looking for an executable file named "python" along PATH. You can
change this by calling Py_SetProgramName(filename) before calling
Py_Initialize(). This is documented in API reference manual:

http://docs.python.org/api/embedding.html

That page also describes a few hooks that you can overwrite to
modify the initial search path. They are described in more detail
on this page:

http://docs.python.org/api/initialization.html

HTH,
Ziga





More information about the Python-list mailing list