gpt4 book ai didi

python - PyImport_Import 失败(返回 NULL)

转载 作者:太空狗 更新时间:2023-10-29 20:45:58 25 4
gpt4 key购买 nike

我是 python 的新手,所以这可能是一个愚蠢的问题。我想用嵌入式 python 脚本编写简单的 c 程序。我有两个文件:

调用函数.c:

    #include <Python.h>
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;

if (argc < 3)
{
printf("Usage: exe_name python_source function_name\n");
return 1;
}

// Initialize the Python Interpreter
Py_Initialize();

// Build the name object
if ((pName = PyString_FromString(argv[1])) == NULL) {
printf("Error: PyString_FromString\n");
return -1;
}

// Load the module object
if ((pModule = PyImport_Import(pName)) == NULL) {
printf("Error: PyImport_Import\n");
return -1;
}

// pDict is a borrowed reference
if ((pDict = PyModule_GetDict(pModule))==NULL) {
printf("Error: PyModule_GetDict\n");
return -1;
}
...

你好.py:

def hello():
print ("Hello, World!")

我按如下方式编译和运行它:

gcc -g -o call-function call-function.c -I/usr/include/python2.6 -lpython2.6
./call-function hello.py hello

并拥有这个:

Error: PyImport_Import

即PyImport_Import 返回 NULL。你能帮我解决这个问题吗?任何帮助将不胜感激。

祝愿

亚历克斯

最佳答案

我通过将 PYTHONPATH 设置为 pwd 解决了这个问题。还应为 argv[1] 设置模块名称(不带 .py)。

谢谢!

关于python - PyImport_Import 失败(返回 NULL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17532371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com