Cython,官方在首页标题就给出了解释,C-Extensions for Python,即python的c扩展。它是一种可以像写python一样轻松地为python语言编写c扩展程序的编程语言,话不多说,用代码解释,哈哈
安装cython
安装cython 1
pip install Cython
cython 的hello world
创建一个文件,“hello.pyx”,写入代码
cython hello world 1
2
3
4
5
6
7def say_hello():
print("hello world!")
def test_c_define():
cdef int a = 0
for i in range(10):
a += i
print(a)创建文件“setup.py”,写入代码:
setup.py 1
2
3
4
5from distutils.core import setup
from Cython.Build import cythonize
setup(name='Hello world app',
ext_modules=cythonize("hello.pyx"))编译:
1
python setup.py build_ext --inplace
编译成功后,目录下会多处两个文件,hello.c、hello.so,现在进入ipython后可以直接倒入hello模块了
如果觉得手动编译很麻烦,还可以在程序内部导入pyximport模块,具体使用如下:1
2
3
4
5
6
7
8
9
10
11
12
13In [1]: import pyximport; pyximport.install()
Out[1]: (None, <pyximport.pyximport.PyxImporter at 0x111307450>)
In [2]: import hello
/Users/storm/.virtualenvs/py2cpython/lib/python2.7/site-packages/Cython/Compiler/Main.py:367: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /Users/storm/Desktop/cpython_test/hello.pyx
tree = Parsing.p_module(s, pxd, full_module_name)
In [3]: hello.say_hello()
hello world!
In [4]: hello.test_c_define()
45
更多cython语法可以参考官方文档