Python 项目转化为so文件实例


Posted in Python onDecember 23, 2019

思路是先将py转换为c代码,然后编译c为so文件,所以要安装以下内容:

python 安装:cython

pip install cython

linux 安装:python-devel,gcc

yum install python-devel
yum install gcc

初步编译

新建Test.py文件,内容如下

class test:
  
  def __init__(self):
    print('init')

  def say(self):
    print ('hello')

新建setup.py,内容如下

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules = cythonize(["Test.py"]))

在bash中执行

python setup.py build_ext

运行后会生成build文件夹,如下

Python 项目转化为so文件实例

现在so文件就可以像普通py文件一样导入了

Python 项目转化为so文件实例

集成编译

做了以下内容:

1.文件夹编译

2.删除编译出的.c文件

3.删除编译的temp文件夹

将需要编译的目录和setup.py放在同一层级,执行python setup.py,so文件在build目录下

setup.py代码如下:

'''
Created on 2019年3月27日

@author: hylink
'''
#-* -coding: UTF-8 -* -

"""
执行前提:
  系统安装python-devel 和 gcc
  Python安装cython

编译整个当前目录:
  python py-setup.py
编译某个文件夹:
  python py-setup.py BigoModel

生成结果:
  目录 build 下

生成完成后:
  启动文件还需要py/pyc担当,须将启动的py/pyc拷贝到编译目录并删除so文件

"""

import sys, os, shutil, time
from distutils.core import setup
from Cython.Build import cythonize

starttime = time.time()
currdir = os.path.abspath('.')
parentpath = sys.argv[1] if len(sys.argv)>1 else ""
setupfile= os.path.join(os.path.abspath('.'), __file__)
build_dir = "build"
build_tmp_dir = build_dir + "/temp"

def getpy(basepath=os.path.abspath('.'), parentpath='', name='', excepts=(), copyOther=False,delC=False):
  """
  获取py文件的路径
  :param basepath: 根路径
  :param parentpath: 父路径
  :param name: 文件/夹
  :param excepts: 排除文件
  :param copy: 是否copy其他文件
  :return: py文件的迭代器
  """
  fullpath = os.path.join(basepath, parentpath, name)
  for fname in os.listdir(fullpath):
    ffile = os.path.join(fullpath, fname)
    #print basepath, parentpath, name,file
    if os.path.isdir(ffile) and fname != build_dir and not fname.startswith('.'):
      for f in getpy(basepath, os.path.join(parentpath, name), fname, excepts, copyOther, delC):
        yield f
    elif os.path.isfile(ffile):
      ext = os.path.splitext(fname)[1]
      if ext == ".c":
        if delC and os.stat(ffile).st_mtime > starttime:
          os.remove(ffile)
      elif ffile not in excepts and os.path.splitext(fname)[1] not in('.pyc', '.pyx'):
        if os.path.splitext(fname)[1] in('.py', '.pyx') and not fname.startswith('__'):
          yield os.path.join(parentpath, name, fname)
        elif copyOther:
            dstdir = os.path.join(basepath, build_dir, parentpath, name)
            if not os.path.isdir(dstdir): os.makedirs(dstdir)
            shutil.copyfile(ffile, os.path.join(dstdir, fname))
    else:
      pass

#获取py列表
module_list = list(getpy(basepath=currdir,parentpath=parentpath, excepts=(setupfile)))
try:
  setup(ext_modules = cythonize(module_list),script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
except Exception as e:
  print (e)
else:
  module_list = list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), copyOther=True))
module_list = list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), delC=True))
if os.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir)
print ("complate! time:", time.time()-starttime, 's')

注意问题

1.编译后执行需要相同的python版本和编码

2.py中使用__file__内置变量的文件编译后调用时会出问题,暂时没有解决,还需要使用pyc代替

3.使用时注意权限控制

以上这篇Python 项目转化为so文件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python open读写文件实现脚本
Sep 06 Python
python将多个文本文件合并为一个文本的代码(便于搜索)
Mar 13 Python
Python中的super用法详解
May 28 Python
举例讲解Django中数据模型访问外键值的方法
Jul 21 Python
Windows下的Jupyter Notebook 安装与自定义启动(图文详解)
Feb 21 Python
uwsgi+nginx部署Django项目操作示例
Dec 04 Python
python http基本验证方法
Dec 26 Python
python3.x+pyqt5实现主窗口状态栏里(嵌入)显示进度条功能
Jul 04 Python
关于Python 常用获取元素 Driver 总结
Nov 24 Python
jupyter notebook 添加kernel permission denied的操作
Apr 21 Python
python2.7使用scapy发送syn实例
May 05 Python
解决pytorch 数据类型报错的问题
Mar 03 Python
python 解决cv2绘制中文乱码问题
Dec 23 #Python
python 实现查询Neo4j多节点的多层关系
Dec 23 #Python
python 多进程队列数据处理详解
Dec 23 #Python
python3实现从kafka获取数据,并解析为json格式,写入到mysql中
Dec 23 #Python
python读取ini配置文件过程示范
Dec 23 #Python
python读取Kafka实例
Dec 23 #Python
Python3 使用selenium插件爬取苏宁商家联系电话
Dec 23 #Python
You might like
根德Grundig S400/S500/S700电路分析
2021/03/02 无线电
收集的php编写大型网站问题集
2007/03/06 PHP
str_replace只替换一次字符串的方法
2013/04/09 PHP
PHP答题类应用接口实例
2015/02/09 PHP
详解PHP序列化反序列化的方法
2015/10/27 PHP
php导出csv文件,可导出前导0实例代码
2016/11/16 PHP
TP5框架实现自定义分页样式的方法示例
2020/04/05 PHP
Jquery网页出现的乱码问题的三种解决方法
2013/06/30 Javascript
GRID拖拽行的实例代码
2013/07/18 Javascript
让input框实现类似百度的搜索提示(基于jquery事件监听)
2014/01/31 Javascript
JQuery对表格进行操作的常用技巧总结
2014/04/23 Javascript
jQuery标签编辑插件Tagit使用指南
2015/04/21 Javascript
JavaScript数组各种常见用法实例分析
2015/08/04 Javascript
jQuery+css实现的时钟效果(兼容各浏览器)
2016/01/27 Javascript
jQuery获取this当前对象子元素对象的方法
2016/11/29 Javascript
Bootstrap基本样式学习笔记之图片(6)
2016/12/07 Javascript
AngularJS基于ui-route实现深层路由的方法【路由嵌套】
2016/12/14 Javascript
Koa项目搭建过程详细记录
2018/04/12 Javascript
JS引用传递与值传递的区别与用法分析
2018/06/01 Javascript
小程序识别身份证,银行卡,营业执照,驾照的实现
2019/11/05 Javascript
JavaScript将数组转换为链表的方法
2020/02/16 Javascript
[03:42]2016国际邀请赛中国区预选赛首日现场玩家采访
2016/06/26 DOTA
在Python的Django框架中更新数据库数据的方法
2015/07/17 Python
使用python根据端口号关闭进程的方法
2018/11/06 Python
python aiohttp的使用详解
2019/06/20 Python
python实现简单的购物程序代码实例
2020/03/03 Python
Python实现子类调用父类的初始化实例
2020/03/12 Python
什么是python的必选参数
2020/06/21 Python
Python matplotlib读取excel数据并用for循环画多个子图subplot操作
2020/07/14 Python
使用HTML5进行SVG矢量图形绘制的入门教程
2016/02/19 HTML / CSS
印度第一网上礼品店:IGP.com
2020/02/06 全球购物
日语专业个人求职信范文
2014/02/02 职场文书
中学教师教育感言
2014/02/21 职场文书
课堂打架检讨书200字
2014/11/21 职场文书
2014年幼儿园学期工作总结
2014/12/05 职场文书
Matlab如何实现矩阵复制扩充
2021/06/02 Python