1. 使用cythonize函数
新建如下目录结构:
test/
├── hello.py
└── setup.py
文件内容如下:
hello.py :
def hello():
print('hello!')
setup.py :
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize(["hello.py"]))
然后执行以下命令:
python setup.py build_ext
然后新生成的build/lib*/hello.so
目录下的就是我们想要的。
进入到build/lib*
目录,执行python
>>> import hello
>>> hello.hello()
hello!
2. 使用cython提供的build_ext
更改setup.py
为:
from distutils.core import setup
from Cython.Distutils import build_ext
from distutils.extension import Extension
setup(
ext_modules = [Extension('hello', ['hello.py'])],
cmdclass = {'build_ext': build_ext},
)
其余步骤和上面一样。
Ref