思路是先将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文件夹,如下



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

集成编译

做了以下内容:

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文件的更多相关文章

  1. Python项目生成requirements.txt文件及pip升级问题解决及流程

    缘由:新项目使用Python, PC上的python包不全,需要通过requirements.txt文件指定安装所需包 pip安装遇到一些坑 一.直接使用pip包管理工具生成requirements. ...

  2. 把Python项目打包成exe文件

    我们很多时候,写好的程序需要打包成.exe文件才可以发给客户,那么今天我就来谈一谈,如何将一个写好的Python程序打包成exe文件! 首先,我们我们使用到的工具是python 3.7 和 Pyins ...

  3. Python项目打包成exe文件

    这里我们使用pyinstaller这个软件即可,使用pip即可完美安装,在要打包的程序目录下打开cmd输入 pyinstaller -F 文件名.py 即可成功,运行成功后生成一个dict文件夹,东西 ...

  4. Python项目生成requirements.txt文件之pipreqs的使用

    生成requirements.txt时使用pip freeze > requirements.txt会将环境下所有的安装包都进行生成,再进行安装的时候会全部安装很多没有的包.耗时耗力其实是不可取 ...

  5. pyinstaller使用-python项目转换成exe可执行文件

    http://blog.csdn.net/pipisorry/article/details/50620122 Python不是每个人的计算机里面都有安装,当您写了一个好用的工具,需要一个standa ...

  6. python 项目部署virtualenv

    安装virtualenv---------------------------------------- mac: pip3 install virtualenv ubuntu: apt instal ...

  7. Pyton项目打包成exe文件

    Python项目打包成exe文件 1 系统环境 windows版本: Win7 64位 python环境:Anaconda python版本:3.6 64位 pyinstaller版本:3.5 1 安 ...

  8. 将Python项目打包成EXE可执行文件(单文件,多文件,包含图片)

    解决 将Python项目打包成EXE可执行文件(单文件,多文件,包含图片) 1.当我们写了一个Python的项目时,特别是一个GUI项目,我们特备希望它能成为一个在Windows系统可执行的EXE文件 ...

  9. python 项目中包中__init__.py文件的作用

    开发python项目时,我遇到了一个这样的现象,当我新建一个pythonpackage时,总会自动地生成一个空的__init__.py文件,因为是python新手,所以很不了解这个空文件的作用是什么, ...

随机推荐

  1. python中继承、定制类

    2.4python中继承 继承中不要忘了调用super().__init__ def __init__(self,args) super(subclass,self).__init___(args) ...

  2. windows7 中 wacom数位板如何关闭点击水波 和长按右键这两个特效

    就是点住笔尖不动,就会弹出右键,这个功能是微软操作系统具有的一项功能,,如果您感觉不便,可以按以下方法将其去掉: 1.打开"控制面板--笔和触摸--笔选项--按下并保持--设置": ...

  3. [LeetCode]-011-Container_With_Most_Water

    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).  ...

  4. Java之Integer类

    Integer类简介: Integer类是基本数据类型int的包装器类,是抽象类Number的子类,位于java.lang包中. Integer类在对象中包装了一个基本类型int的值,也就是每个Int ...

  5. hibernate注解创建表总是失败,显示表不存在

    import java.io.Serializable; import javax.persistence.*; import org.hibernate.annotations.GenericGen ...

  6. JavaScript判断 Radio 单选按钮是否为选中状态 并弹出 值信息

    今天在百度前端任务中遇到了一个以前没怎么注意的知识点,所以就准备记下来 <script type="text/javascript"> //判断个函数 以上 5 个Ra ...

  7. 阶段3 1.Mybatis_06.使用Mybatis完成DAO层的开发_2 Mybatis中编写dao实现类的使用-保存操作

    再完善.saveUser的方法 测试保存的操作 报错了 SqlSession的insert的源码 我们在执行Insert的时候,并没有把user对象传过去 usersex改成sex 再次测试

  8. gzip, deflate delphi xe 2 解码 成功 哈哈

    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 http://bbs.csdn.net/topics/190020986   ...

  9. 读取数据库 生成Xml节点

    foreach (DataColumn v in dt.Columns) { sb.Append("sb.Append(\"<" + v.ColumnName.To ...

  10. HTML5 表单的补充+注意事项

    input标签中  type="image" 与 type="submit"属性   的区别    (下文简写image和submit) 1.这两者都可以响应请 ...