1. 程式人生 > 其它 >CentOS 7 下通過 Cython 編寫 python 擴充套件

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