不能从Python导入modu方法

2024-09-28 19:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建使用Python插件的C应用程序。当尝试从另一个Python模块调用该方法时,PyImport_ImportModule()似乎正确地导入了该模块,然后我尝试使用PyObject_GetAttrString()从该模块获取该函数,得到的结果是null。在

我已经尝试使用PyModule_GetDict()PyDict_GetItemString()从模块中获取方法,但是效果是一样的。在

主控室:

#include <stdio.h>
#include <python3.6/Python.h>

int main()
{
    PyObject *arg, *pModule, *ret, *pFunc, *pValue, *pMethod, *pDict;
    Py_Initialize();
    PyObject *sys = PyImport_ImportModule("sys");
    PyObject *path = PyObject_GetAttrString(sys, "path");
    PyList_Append(path, PyUnicode_FromString("."));

    pModule = PyImport_ImportModule("test");
    if(pModule == NULL)
    {
        perror("Can't open module");
    }
    pMethod = PyObject_GetAttrString(pModule, "myfun");
    if(pMethod == NULL)
    {
        perror("Can't find method");
    }

    ret = PyEval_CallObject(pMethod, NULL);
    if(ret == NULL)
    {
        perror("Couldn't call method");
    }

    PyArg_Parse(ret, "&d", pValue);
    printf("&d \n", pValue);

    Py_Finalize();
    return 0;
}

在测试.py公司名称:

^{pr2}$

我得到的结果是:

Can't find method: Success
Segmentation fault (core dumped)

当我使用gdb调试器时,输出是:

pModule = (PyObject *) 0x7ffff5a96f48
pMethod = (PyObject *) 0x0

Tags: 模块pathifsysnullcanpyobjectret
1条回答
网友
1楼 · 发布于 2024-09-28 19:34:21

您的程序没有编写,因为要导入的模块是^{} built-in module,而不是您的test.py脚本。这是因为您正在将当前目录附加到sys.path,因此它会在列表中其他已存在路径之后进行检查。您应该将其插入到列表的开头,以便先检查它。在

这将起作用:

PyObject *sys = PyImport_ImportModule("sys");                                                                                                                                                                     
PyObject *path = PyObject_GetAttrString(sys, "path");                                                                                                                                                     
PyList_Insert(path, 0, PyUnicode_FromString("."));

顺便说一下,您应该先#includePython头,如文档中所述:

Note: Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.

相关问题 更多 >