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 總要麻煩一些吧
參考文檔: