embedding python - PyImport_ImportModule returns null

Alex Martelli aleax at aleax.it
Thu Mar 6 05:25:03 EST 2003


JW wrote:

> I am trying to embed python within a c program, but I can't get
> PyImport_ImportModule() command to load my module.
> Please let me know what I'm doing wrong.
   ...
> Both main.c and func.py are in the same directory.
> I run main and get the error
> Failed to load "func", meaning that PyImport_ImportModule returns NULL.

The current directory is not necessarily on sys.path.  Notice:

[alex at lancelot nubal]$ ./a.out
ImportError: No module named func
Failed to load "func"
[alex at lancelot nubal]$ PYTHONPATH=. ./a.out
inside func1()
[alex at lancelot nubal]$

I'm using the same code you posted plus the needed #include <Python.h>,
PyObject_CallMethod, and Py_Finalize.

You do need to ensure that the directories housing the modules you
want to import are on sys.path.  For example, if you know they'll
be in your current directory, just add the line:

        PySys_SetPath(".");

before you call PyImport_ImportModule, and your example will work.


Alex





More information about the Python-list mailing list