I would like to create an embedded python 3 interpreter and let python scripts import modules created via the C Python API.
No problem to create a "top-level" module, but now I would like to organized my modules in packages ... But I failed.
Here is my current (simple) code :
#include <Python.h>
//// Definition of 'emb.sub' module
static PyObject* emb_sub_foo(PyObject *self, PyObject *args)
{
char const* n = "I am sub foo";
return Py_BuildValue("s", n);
}
static PyMethodDef EmbSubMethods[] = {
{"foo", emb_sub_foo, METH_VARARGS, "Returns sub foo"},
{NULL, NULL, 0, NULL}
};
static PyModuleDef EmbSubModule = {
PyModuleDef_HEAD_INIT, "emb.sub", NULL, -1, EmbSubMethods,
NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb_sub(void)
{
return PyModule_Create(&EmbSubModule);
}
//// Embedded Python
int main()
{
PyImport_AppendInittab("emb.emb", &PyInit_emb_sub);
Py_Initialize();
PyRun_SimpleString("import emb.sub\n");
Py_Finalize();
return 0;
}
When I executes the program, I get :
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named 'emb'
So I create an empty emb module, and I set its __path__ like this :
#include <Python.h>
//// Definition of 'emb' module
static PyModuleDef EmbModule = {
PyModuleDef_HEAD_INIT, "emb", NULL, -1, NULL,
NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb(void)
{
PyObject *mod = PyModule_Create(&EmbModule);
PyModule_AddObject(mod, "__path__", Py_BuildValue("()"));
return mod;
}
//// Definition of 'emb.sub' module
static PyObject* emb_sub_foo(PyObject *self, PyObject *args)
{
char const* n = "I am sub foo";
return Py_BuildValue("s", n);
}
static PyMethodDef EmbSubMethods[] = {
{"foo", emb_sub_foo, METH_VARARGS, "Returns sub foo"},
{NULL, NULL, 0, NULL}
};
static PyModuleDef EmbSubModule = {
PyModuleDef_HEAD_INIT, "emb.sub", NULL, -1, EmbSubMethods,
NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb_sub(void)
{
return PyModule_Create(&EmbSubModule);
}
//// Embedded Python
int main()
{
PyImport_AppendInittab("emb", &PyInit_emb);
PyImport_AppendInittab("emb.sub", &PyInit_emb_sub);
Py_Initialize();
PyRun_SimpleString("import emb.sub\n");
Py_Finalize();
return 0;
}
And now I get this error :
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named 'emb.sub'
I would like to know if it is possible to create a hierarchy of packages and modules in embedded python ?
Thanks !