cython安装、使用

cython安装、使用

原创 2012年09月27日 17:25:11
  • 8436
  • 0
  • 0

一、cython 在linux(ubuntu)下安装

 

sudo apt-get install cython

安装后  输入 cython 即可验证是否安装成功

 

二、 使用 

1、编写   以 .pyx为扩展名的 cython程序,hello.pyx

 

[python]  view plain  copy
 
  1. def say_hello_to(name):  
  2.     print("Hello %s!" % name)  

 2、编写python程序 setup.py,其目的是把 hello.pyx程序转化成hello.c ,并编译成so文件

 

 

[python]  view plain  copy
 
  1. from distutils.core import setup  
  2. from distutils.extension import Extension  
  3. from Cython.Distutils import build_ext  
  4.   
  5. ext_modules = [Extension("hello", ["hello.pyx"])]  
  6.   
  7. setup(  
  8.   name = 'Hello world app',  
  9.   cmdclass = {'build_ext': build_ext},  
  10.   ext_modules = ext_modules  
  11. )  

3. 执行python程序

 

 

[python]  view plain  copy
 
  1. zero@zero:~$ python setup.py build_ext --inplace  

执行的结果会生成两个文件:hello.c 和 hello.so( 用PyObject* 封装好的文件)

 

4. 用python调用 hello.so,调用文件为test.py

 

[python]  view plain  copy
 
  1. import hello  
  2.   
  3. hello.say_hello_to("hi,cython!!")  


 

cython的主要目的是: 简化python调用c语言程序的繁琐封装过程,提高python代码执行速度(C语言的执行速度比python快)

 

你可能感兴趣的:(cython安装、使用)