1 Cython的代码的构建过程
Cython的代码是需要编译的,与C/C++类似,用Cython写的.pyx
文件需要两步编译:
(1).pyx
文件由Cython编译生成.c
文件
(2).c
文件由c编译器编译成为.so
文件,这个文件就可以用python进行 import
并使用了。
2 构建Cython代码的方法
有多种构建方案可以选择:
-
官方推荐方法
编写一个setuptools文件:setup.py
,然后在python终端执行以下命令,即可完成1中所提到的编译过程:
python setup.py build_ext --inplace
-
使用
Pyximport
通过Pyximport
来导入.pyx
文件,这与导入.py
是类似的。这种方法其实是后台在隐式地执行(compile和biuld),但是当你需要指定某些编译选项的时候,你还是得写一个setup.py
. -
命令方法
使用cython命令行从.pyx
手动生成.c
文件,然后敲命令从.c
手动生成DLL或者shared object library这种适合python导入的动态库. -
Jupyter中的使用
在Jupyter中使用Cpython比较简单,直接看下面案例吧。
3 动手操练
3.1 使用setupytools构建Cython模块
- 首先来创建第一个cython文件吧,命名为
hello.pyx
,在文件中定义:
#@file: hello.pyx
def say_hello_to(name):
print("Hello %s!" % name)
- 然后创建相应的
setup.py
:
from setuptools import setup
from Cython.Build import cythonize
setup(
name='Hello world app',
ext_modules=cythonize("hello.pyx"),
zip_safe=False,
)
- 在该文件夹的终端中执行以下命令:
python setup.py build_ext --inplace
你会看到文件夹下生成了hello.c
文件还有.so
或者pyd
文件 - 下面试试在我们的python程序中导入刚刚的cython模块(与导入python模块完全一样),新建一个
hello_world.py
文件:
#@file: hello_world.py
import hello
hello.say_hello_to('World')
然后运行hello_world.py
,得到下面的输出:
(base) D:\cython>H://Anaconda//python.exe d:/cython/hello_world.py
Hello World!
大功告成!
需要额外注意(初学者略过):
the default action when running python setup.py install is to create a zipped egg file which will not work with cimport for pxd files when you try to use them from a dependent package. To prevent this, include zip_safe=False in the arguments to setup().
3.2 Jupyter notebook版本
在Jupyter中,通过%load_ext Cython
来导入Cython的扩展,然后,为单元格添加%%cython
标记以对其进行编译。Jupyter的魔法命令还可以查看Cython的代码分析%%cython --annotate
官方示例如下,来试试吧!
image.png