cython安装、使用
一、cython 在linux(ubuntu)下安装
sudo apt-get install cython
安装后 输入 cython 即可验证是否安装成功
二、 使用
1、编写 以 .pyx为扩展名的 cython程序,hello.pyx
- def say_hello_to(name):
- print("Hello %s!" % name)
2、编写python程序 setup.py,其目的是把 hello.pyx程序转化成hello.c ,并编译成so文件
- from distutils.core import setup
- from distutils.extension import Extension
- from Cython.Distutils import build_ext
- ext_modules = [Extension("hello", ["hello.pyx"])]
- setup(
- name = 'Hello world app',
- cmdclass = {'build_ext': build_ext},
- ext_modules = ext_modules
- )
3. 执行python程序
- zero@zero:~$ python setup.py build_ext --inplace
执行的结果会生成两个文件:hello.c 和 hello.so( 用PyObject* 封装好的文件)
4. 用python调用 hello.so,调用文件为test.py
- import hello
- hello.say_hello_to("hi,cython!!")
cython的主要目的是: 简化python调用c语言程序的繁琐封装过程,提高python代码执行速度(C语言的执行速度比python快)