简体   繁体   English

如何在python 3.x中初始化模块以便可以导入?

[英]How to initialize a module in python 3.x so that it can be imported?

In Python 2.7 I'd do Python 2.7中,我愿意

void InitPython()
{
    ..
    Py_InitModule3("my_prog", ProgMethods, "documentation");
    ..
}

Then I will simply be able to do import my_prog like this in my code 然后,我将能够像这样在我的代码中import my_prog

char strCode[] = "import my_prog, sys, os\n"

PyRun_SimpleString (strCode); PyRun_SimpleString (strCode);


However in Python 3.6 , following the official documentation and applying the changes doesn't work 但是在Python 3.6中 ,遵循官方文档并应用更改无效

static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,
    "my_prog",                          /* m_name */
    "documentation",                    /* m_doc */
    -1,                                 /* m_size */
    ProgMethods,                        /* m_methods */
    NULL,                               /* m_reload */
    NULL,                               /* m_traverse */
    NULL,                               /* m_clear */
    NULL,                               /* m_free */
};

void InitPython()
{
    ..
    PyObject *m1 = PyModule_Create(&moduledef);
    ..
}

Fails with following error: 失败,并出现以下错误:

ModuleNotFoundError: No module named 'my_prog' ModuleNotFoundError:没有名为“ my_prog”的模块

How to fix this? 如何解决这个问题?

The documentation I can find says your initialization function should be named PyInit_mymodule and marked with PyMODINIT_FUNC : 我可以找到文档说您的初始化函数应命名为PyInit_mymodule并标有PyMODINIT_FUNC

static PyMethodDef SpamMethods[] = {
    // ...
    {"system",  spam_system, METH_VARARGS, "Execute a shell command."},
    // ...
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

// ...

static struct PyModuleDef spammodule = {
    PyModuleDef_HEAD_INIT,
    "spam",
    spam_doc,
    -1,
    SpamMethods
};

// ...

PyMODINIT_FUNC
PyInit_spam(void)
{
    return PyModule_Create(&spammodule);
}

(As an aside, unless you really do need to create your extension in C, I'd recommend looking at Cython too.) 顺便说一句 ,除非您确实需要使用C创建扩展名,否则我建议您也查看Cython 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM