前文参见 《CentOS 7 下通过 Cython 编写 python 扩展 》, 用的是 Python2.7,本文用的是 Python3.6
yum install pthon3 python3-devel gcc
pip3 install Cython -i https://pypi.tuna.tsinghua.edu.cn/simple
创建 pyx 文件与前文一致
python3 setup.py -build_ext --inplace
如遇到出错,报告
hello.c:2264:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
表示当前的 gcc 4.8.5 默认仅支持 C89 标准, 不兼容在 for 中定义循环变量,搜索一圈没找到如何在 setup.py 中传参支持 -std=c99,ChatGPT 倒是给了个方案
from setuptools import setup, Extension
extensions = [Extension("your_module", ["your_module.pyx"], extra_compile_args=["-std=c99"])]
etup(
ext_modules=extensions,
# other setup parameters...
)
可惜运行下来还是一样的错误,还尝试过添加文件头
# distutils: language=c++
# distutils: define_macros=PY_SSIZE_T_CLEAN
# cython: language_level=3
# cython: extra_compile_args=['-std=c99']
也不解决问题。好在已经生成了 hello.c,于是参考控制台输出自己手动完成后续编译
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -O2 \
-g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions \
-fstack-protector-strong --param=ssp-buffer-size=4 \
-grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE \
-fPIC -fwrapv -fPIC -I/usr/include/python3.6m -c hello.c -o \
hello.o -std=c99
不错,生成了 hello.o 之后,再通过
gcc -shared hello.o -o hello.so
终于得到了 hello.so 文件,运行调用
python3 hello.py
输出
Hello cython
尝试通过Python2 调用会报错
python hello.py
ImportError: /root/hello_pack/hello.so: undefined symbol: _Py_FalseStruct
应该是不兼容 Python2
- CentOS7 Python3 CentOS Python Cythoncentos7 python3 centos python 镜像centos7 python3 fastapi 第三方 仓库centos7 python3 centos7 python3环境centos python3 centos python python3 centos python numpy mysqlclient python3 centos python centos6 python3 django1 centos python3 centos python module python3教程centos python