一、环境准备
? ? 安装cython,以及gcc编译环境
? ? wget https://bootstrap.pypa.io/get-pip.py
? ? python get-pip.py
? ? pip install cython
? ? yum install -y gcc python-devel
二、编写测试脚本
? ?test.py,内容如下
? ?import os
? ?def test():
? ? ? ?print ?os.path.realpath(‘.‘)
? ?
三、将其拷贝到python系统路径
? ? /usr/lib/python2.7/site-packages/test
? ? 在test目录下创建__init__.py,与 test.py 的文件
? ? test.py 上面内容如上所示
四、脚本测试
? ? python?
? ? >>> import lyh.test
? ? >>> lyh.test.test()
五、编译so文件
? ? 以下操作均在 /usr/lib/python2.7/site-packages/test 路径下执行
? ??
? ? 1. cython test.py
? ? 2. gcc -c -fPIC -I/usr/include/python2.7/ test.c
? ? 3. gcc -shared test.o -o test.so
? ??
六、验证so文件的可用性
? ? 1. 移除/usr/lib/python2.7/site-packages/test/test.py 文件,只保留 test.so文件
? ? ? ? test
? ? ? ? ├── __init__.py
? ? ? ? └── test.so
? ? 2.?
? ? python
? ? >>> import test.test
? ? >>> test.test.test()
? ??
? ? 可以执行
? ? 验证完成
?
七、使用setup.py 编译so
? ? 1. 编写setup.py文件,位于/usr/lib/python2.7/site-packages/test,内容如下:
? ??
? ? from distutils.core import setup
? ? from Cython.Build import cythonize
? ? setup(
? ? ? ? ext_modules = cythonize("test.py")
? ? )
? ? 2.然后运行
? ? ? ? setup.py build_ext --inplace