Cython系列教程:二. 构建Cython代码

2020-11-29  本文已影响0人  DeepNLPLearner

1 Cython的代码的构建过程

Cython的代码是需要编译的,与C/C++类似,用Cython写的.pyx文件需要两步编译:
(1).pyx文件由Cython编译生成.c文件
(2).c文件由c编译器编译成为.so文件,这个文件就可以用python进行 import 并使用了。


2 构建Cython代码的方法

有多种构建方案可以选择:


3 动手操练

3.1 使用setupytools构建Cython模块

#@file: hello.pyx
def say_hello_to(name):
    print("Hello %s!" % name)
from setuptools import setup
from Cython.Build import cythonize

setup(
    name='Hello world app',
    ext_modules=cythonize("hello.pyx"),
    zip_safe=False,
)
#@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
上一篇 下一篇

猜你喜欢

热点阅读