我在 CentOS 7 上将 Python 3 与 Anaconda Spyder 一起使用。我正在尝试按照此视频使 Python CExtension 正常工作。 https://www.youtube.com/watch?v=a65JdvOaygM
我的所有文件都在 PYTHONPATH 中的 /home/peter/pythonCExtensions 中
我有一个包含以下内容的文件 myModule.c。
#include <stdio.h>
#include <stdlib.h>
#include "/home/peter/anaconda3/include/python3.7m/Python.h"
int Cfib(int n)
{
if (n<2){
return n;
} else {
return Cfib(n-1)+Cfib(n-2);
}
}
static PyObject* fib(PyObject* self, PyObject* args)
{
int n;
if (!PyArg_ParseTuple(args, "i", &n))
return NULL;
return Py_BuildValue("i", Cfib(n));
}
static PyObject* version(PyObject* self){
return Py_BuildValue("s", "Version 1.0");
}
static PyMethodDef myMethods[] = {
{"fib", fib, METH_VARARGS, "Calculates the Fibronacci numbers"},
{"version", (PyCFunction)version, METH_NOARGS, "Returns the version"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef myModule = {
PyModuleDef_HEAD_INIT,
"myModule",
"Fibronacci Module",
-1,
myMethods
};
PyMODINIT_FUNC PyInit_myModule(void){
return PyModule_Create(&myModule);
}
我制作了另一个文件 setup.py,它具有以下内容。
from distutils.core import setup, Extension
module = Extension("MyModule", sources = ["myModule.c"])
setup(name="PackageName",
version="1.0",
description="This is a package for myModule",
ext_modules = [module])
我跑了
python3 setup.py install
并得到
running install
running build
running build_ext
running install_lib
copying build/lib.linux-x86_64-3.7/MyModule.cpython-37m-x86_64-linux-gnu.so -> /home/peter/anaconda3/lib/python3.7/site-packages
running install_egg_info
Writing /home/peter/anaconda3/lib/python3.7/site-packages/PackageName-1.0-py3.7.egg-info
然后我将 MyModule.cpython-37m-x86_64-linux-gnu.so 和 myModule.o 复制到 /home/peter/pythonCExtensions 中。
然后我打开 Spyder 并创建了一个文件 CInterface.py,它只包含
import myModule
但是,当我运行此文件(F5)时,我得到
Traceback (most recent call last):
File "<ipython-input-1-c29fad851da0>", line 1, in <module>
runfile('/home/peter/Simple3dShapes/CInterface.py', wdir='/home/peter/Simple3dShapes')
File "/home/peter/anaconda3/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "/home/peter/anaconda3/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/peter/Simple3dShapes/CInterface.py", line 19, in <module>
import myModule
ModuleNotFoundError: No module named 'myModule'
sudo yum install tree
导致
安装 1 个软件包
Total download size: 46 k
Installed size: 87 k
Is this ok [y/d/N]: y
Downloading packages:
tree-1.6.0-10.el7.x86_64.rpm | 46 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : tree-1.6.0-10.el7.x86_64 1/1
Verifying : tree-1.6.0-10.el7.x86_64 1/1
Installed:
tree.x86_64 0:1.6.0-10.el7
Complete!