Python/C and PYTHONPATH

Jeff Epler jepler at unpythonic.net
Tue Jan 6 04:10:34 CET 2004


On Mon, Jan 05, 2004 at 04:17:52PM +0000, Tero Pihlajakoski wrote:
> Jeff Epler <jepler at unpythonic.net> wrote:
> > You'd need to tell us how you're invoking Python.  When the Python
> 
> Take a look at:  
> http://www.python.org/doc/current/ext/pure-embedding.html.  Basically,
> it's about same (and I tested with it too, same results: failing)

Here's the program I came up with:

#include <Python.h>

int
main(int argc, char *argv[])
{
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PyRun_SimpleString("import sys; print sys.path, sys.executable");
    PySys_SetArgv(argc-1, argv+1);
    PyRun_SimpleString("import sys; print sys.path, sys.executable");
    Py_Finalize();
    return 0;
}

This program demonstrates that the initial sys.path element
corresponding to the location of the script is created when
PySys_SetArgv() is called:

$ ./embed
['/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...]
['', '/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...]

That first element depends on the location of the script, as shown here:

$ ./embed /tmp/x
['/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...]
['/tmp', '/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...]

I don't know where this is documented---PySys_SetArgv is mentioned in
the "api" document, but this side-effect is not:
	http://www.python.org/doc/current/api/embedding.html#l2h-35
	http://www.python.org/doc/current/api/initialization.html#l3h-713
You might want to explore just what PySys_SetArgv and submit a
documentation patch on sourceforge, both for the api document and for
the ext document.  Interestingly, calling PySys_SetArgv multiple times
inserts multiple items in sys.path.

Jeff




More information about the Python-list mailing list