pyx 模板的運行和測試
如果要測試 pyx 模板,可以通過編譯或者動態導入:
- 編譯: setup.py,生成動態庫(linux 為so文件, window pyd),可以直接被 import 引入到一個Python會話中
-
from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize setup( ext_modules = cythonize([Extension("select_by_kp", ["select_by_kp.pyx"])]) )
靜態鏈接,比如鏈接使用 numpy:
- 在 select_by_kp.pyx 中鏈接
-
# distutils: include_dirs = /Users/yangshujun/self/cython_build/venv/lib/python3.7/site-packages/numpy/core/include/ import numpy as np cimport numpy as np from libc.stdio cimport printf # from cython.parallel import prange, parallel, threadid
# distutils: include_dirs 代表:numpy 相關頭文件所在的地方,# distutils: sources 代表:鏈接c源碼的文件
- 在 setup.py ,用過 Extension 包含需要頭文件的目錄
-
numpy_include = np.get_include() setup( cmdclass={'build_ext': build_ext}, ext_modules=cythonize([Extension('select_by_kp', ["select_by_kp.pyx"], include_dirs=[numpy_include, ])]))
或:使用export 添加路徑
-
numpy_include = np.get_include() os.environ['CFLAGS'] = '-I{}'.format(numpy_include) setup( cmdclass={'build_ext': build_ext}, ext_modules=cythonize([Extension('select_by_kp', ["select_by_kp.pyx"])]))
- 通過 Pyximport 導入 Cython .pyx 文件,比如導入 primes1.pyx
-
from distutils import sysconfig import pyximport pyximport.install(pyimport=True, language_level=2) import primes1
可以 這個就可以正常使用了