Do I upload a PyImport_ImportModule file and import into another namespace?

Here's a canonical example of an extension program for embedded Python 3.x in C / C ++:

#include <Python.h>
//// Definition of 'emb' Python module ////////////////////
static PyObject* emb_foo(PyObject *self, PyObject *args)
{
    char const* n = "I am foo";
    return Py_BuildValue("s", n);
}
static PyMethodDef EmbMethods[] = {
    {"foo", emb_foo, METH_VARARGS, "Returns foo"},
    {NULL, NULL, 0, NULL}
};
static PyModuleDef EmbModule = {
    PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
    NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb(void)
{
    return PyModule_Create(&EmbModule);
}
//// Embedded Python with 'emb' loaded ////////////////////
int main()
{
    PyImport_AppendInittab("emb", &PyInit_emb);
    Py_Initialize();

    PyRun_SimpleString("import emb\n");       // (1)
    //PyImport_ImportModule("emb");           // (2)

    PyRun_SimpleString("print(emb.foo())\n"); // (3)

    Py_Finalize();
    return 0;
}

I am adding a module embto the built-in built-in interpreters. I would also like to import it automatically, so users do not need to set an operator import embin their scripts supplied with my built-in interpreter. I am trying to use two import methods in lines (1) and (2) .

(1), emb (3). , (1) (2) API C API Python 3, (3 ) :

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'emb' is not defined

, . / ?

Python 3 :

, , , PyImport_ImportModule --, PyImport_ImportModuleEx ( ?) , "" .

+5
1

__import__ , . import __import__, . docs , import spam - :

spam = __import__('spam', globals(), locals(), [], 0)

C API, emb. , emb __main__.

PyObject* emb_module = PyImport_ImportModule("emb");
PyObject* main_module = PyImport_AddModule("__main__");
PyObject_SetAttrString(main_module, "emb", emb_module);
Py_XDECREF(emb_module);
/* (main_module is a borrowed reference) */
+7

All Articles