CentOS 7 下通过 Cython 编写 python 扩展

1. 安装 python 和 python-devel(没有后者,install 的时候会报错 "Scanners.c:21:20: fatal error: Python.h: No such file or directory")

2. 从 https://pypi.python.org/pypi/Cython/ 下载 Cython-0.29.26.tar.gz

3. 安装 Cython

tar -xvzf Cython-0.29.26.tar.gz
cd Cython-0.29.26.tar.gz
python setup.py install

4. 编写 pyx 脚本

mkdir hello_pack && cd hello_pack

创建 hello.pyx 脚本,定义所需的函数

#coding=utf-8
def print_hello(name):
    print "Hello %s!" % name

5. 编写 setup.py 编译脚本

from distutils.core import setup
from Cython.Build import cythonize
setup(
    name='Hello pyx',
    ext_modules=cythonize('hello.pyx')
)

6. 编译组件

python setup.py build

7. 执行完之后,会生成当前目录下 ./build/lib.linux-x86_64-2.7/hello.so

8. 编写调用脚本 hello.py,放在 hello.so 所在目录

#!/usr/bin/python
# coding=utf-8
import hello
hello.print_hello("cython")

9. 执行 hello.py,输出

Hello cython!

PS: 使用 Cython 的目的一是提升执行效率,另外一个就是实现对 *.py 代码的保护,毕竟反编译 .so 总要麻烦一些吧

参考文档:

Cython的简单使用

fatal error: Python.h: No such file or directory解决办法

centos 7 安装 python-dev包提示No package python-dev available