cython使用初步
1. 为什么要使用cython?
[Cython] is a programming language that makes writing C extensions for the Python language as easy as Python itself.
It aims to become a superset of the [Python] language which gives it high-level, object-oriented, functional, and dynamic programming.
Its main feature on top of these is support for optional static type declarations as part of the language.
The source code gets translated into optimized C/C++ code and compiled as Python extension modules.
This allows for both very fast program execution and tight integration with external C libraries, while keeping up the high programmer
productivity for which the Python language is well known.
简而言之,就是可以结合python与c/c++的优点,既能很好地与C扩展模块交互,降低执行时间,又基本保持了python的编程风格,易于开发。
2. cython相关的几种文件
*.pyx -> *.c
cython会将*.pyx
编译成*.c
。*.c -> *.so/*.pyd
c编译器将*.c
文件编译成*.so
(linux下)或*.pyd
(windows下),python就可以正常import
了。setup.py
打包工具,打包后通过
python setup.py build_ext --inplace --force
执行程序中所有的语句。
- Makefile
可在git bash
下通过make
语句来执行Makefile
中所有的命令。
3. cython小栗子分享
从“hello world”谈起:
3.1 创建cython_hello.pyx
# cython: language_level=3
def hello(name):
print(f"hello {name}")
3.2 创建setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(name="cython_hello",
ext_modules=cythonize("cython_hello.pyx")
)
3.3 创建test.py
调用*.pyd
文件测试效果
from cython_hello import hello
hello("world")
3.4 创建Makefile
文件
all:
python setup.py build_ext --inplace --force
test:
python test.py
clean:
-rm -rf build *.{
c,}
3.5 编译、调用说明
打开Git Bash,cd到工程文件夹。
依次执行:
$ make
执行完这一步后,发现生成了bulid文件夹,*.c, *.pyd文件
。
下一步就是测试。
$ make test
正常输出:
hello world
最后一步是删除中间文件(可选),
$ make clean
这样就删除了bulid文件夹,*.c文件
,而不会影响程序正常的import
。
4.遇到的bug
4.1 FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File
参考https://blog.csdn.net/weixin_42445581/article/details/107201789,在所有的*.pyx
文件第一行添加:
# cython: language_level=3
4.2 TypeError: expected bytes, str found
检查*.pyc
文件中传递的字符串变量,后面加上:
st.encode()
参考http://docs.cython.org/en/latest/src/tutorial/strings.html。
参考文献
[1] cython官方文档
[2] https://blog.csdn.net/weixin_42445581/article/details/107201789