从Python 2迁移到Python 3 - 嵌入问题

0 投票
1 回答
1205 浏览
提问于 2025-04-17 23:21

我正在把一个嵌入了Python的应用程序从2.7版本迁移到3.3版本。这个应用程序通过调用Py_InitModule()来提供一些功能给脚本使用,传入相应的数据。为了让像我这样的可怜人感到困扰,Python 3把这个API给去掉了,换成了PyModule_Create,这个新的方法需要一个比较复杂的结构。

当我使用Python 2的API时,一切都正常,但当我用新的3版本API时,虽然API加载没有问题(返回了一个有效的指针),但是在脚本中使用这些暴露出来的功能时却出现了错误:

//ImportError: No module named 'emb'

这里的'emb'是我的模块名。真让人烦!我同时包含了两个版本的代码,也许有人能帮忙。我参考了这里的迁移指南:

http://docs.python.org/3/howto/cporting.html

这个指南做的事情和我一样。为什么要改这个API我真搞不懂。

static int numargs=0;


static PyObject*
emb_numargs(PyObject *self, PyObject *args) //what this function does is not important
{
    if(!PyArg_ParseTuple(args, ":numargs"))
        return NULL;
    return Py_BuildValue("i", numargs);
}

static PyMethodDef EmbMethods[] = {
    {"numargs", emb_numargs, METH_VARARGS,
    "Return the number of arguments received by the process."},
    {NULL, NULL, 0, NULL}
};


#ifdef PYTHON2

    //works perfect with Pytho 27

    Py_InitModule("emb", EmbMethods);

    PyRun_SimpleString(
        "import emb\n"
        "print(emb.numargs())\n"
        );      

#else


static struct PyModuleDef mm2 = {
    PyModuleDef_HEAD_INIT,
    "emb",
    NULL,
    sizeof(struct module_state),
    EmbMethods,
    NULL,
    0,
    0,
    NULL
};

    //does not work with python 33:
    //ImportError: No module named 'emb'


    PyObject* module = PyModule_Create(&mm2);

    PyRun_SimpleString(
        "import emb\n"
        "print(emb.numargs())\n"
        );

#endif

1 个回答

2

根据这个问题,看起来他们改变了导入模块的方法,相关的文档也有变化

以下是希望能对你有帮助的内容:

// this replaces what is currently under your comments

static PyObject*
PyInit_emb(void)
{
    return PyModule_Create(&mm2);
}

numargs = argc;
PyImport_AppendInittab("emb", &PyInit_emb);

撰写回答