一、环境准备
安装cython,以及gcc编译环境
test.py,内容如下
/usr/lib/python2.7/site-packages/test
在test目录下创建__init__.py, 与 test.py 的文件
test.py 上面内容如上所示
四、脚本测试
六、验证so文件的可用性
1. 移除/usr/lib/python2.7/site-packages/test/test.py 文件,只保留 test.so文件
test
├── __init__.py
└── test.so
2.
安装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 路径下执行
cython test.py
gcc -c -fPIC -I/usr/include/python2.7/ test.c
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
上面是使用gcc将py编译成so,下面直接使用python自带的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
八、第三种方式
见:
python文件编译成so介绍 - 2.使用makefile将py文件编译成so文件并制作成rpm包,实现自动化
http://blog.csdn.net/linshenyuan1213/article/details/79298473