加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用cython将py文件编译成so文件

发布时间:2020-12-17 20:36:52 所属栏目:安全 来源:网络整理
导读:一、环境准备 ? ? 安装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(): ?

一、环境准备
? ? 安装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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读