【发布时间】:2013-07-08 17:15:06
【问题描述】:
我是 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。你能帮我解决这个问题吗?任何帮助将不胜感激。
祝你好运,
亚历克斯
【问题讨论】:
-
你忘记了用鸡血画五边形并点亮黑色蜡烛的步骤:P .... 这通常对我来说在混合 C 和 Python 时有用
-
看起来
argv[0]将是 exe 名称,argv[1]将是hello.py,argv[2]将是hello。你想导入别的东西而不是argv[1]吗?您需要模块名而不是源文件名吗? -
是的,没错。但我认为模块名称与文件名相同。对吗?
-
模块名称为
hello。标准的 python 脚本也是如此。你也不能从本地目录运行python -c "import hello.py"。