embedding python - PyImport_ImportModule returns null
Bjorn Pettersen
BPettersen at NAREX.com
Thu Mar 6 14:44:23 EST 2003
> From: Alex Martelli [mailto:aleax at aleax.it]
>
> 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:
Hi Alex,
Perhaps you would know how to import a module so that it can be used in
PyRun_String()? I've tried PyImpor_Import, PyImport_ImportModule, and
PyImport_ImportModuleEx which all imported the module but didn't make it
visible.
void main() {
Py_Initialize();
PySys_SetPath(Py_GetPath());
PyObject* mainmod = PyImport_AddModule("__main__");
Py_INCREF(mainmod);
PyObject* ns = PyModule_GetDict(mainmod);
Py_INCREF(ns);
PyObject* timeModule = PyImport_ImportModuleEx("time", ns, ns,
NULL);
if (!timeModule) std::cout << getTraceback() << std::endl;
std::cout << "time module imported successfully" << std::endl;
PyObject* timeFn = PyRun_String("time.time", Py_eval_input, ns, ns);
if (!timeFn) std::cout << getTraceback() << std::endl;
Py_XDECREF(timeModule);
Py_XDECREF(timeFn);
Py_DECREF(ns);
Py_DECREF(mainmod);
Py_Finalize();
}
and the output:
Adding parser accelerators ...
Done.
time module imported successfully
Traceback (most recent call last):
File "<string>", line 0, in ?
NameError: name 'time' is not defined
[4099 refs]
-- bjorn
More information about the Python-list
mailing list