Python 项目转化为so文件
思路是先将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文件的更多相关文章
- Python项目生成requirements.txt文件及pip升级问题解决及流程
缘由:新项目使用Python, PC上的python包不全,需要通过requirements.txt文件指定安装所需包 pip安装遇到一些坑 一.直接使用pip包管理工具生成requirements. ...
- 把Python项目打包成exe文件
我们很多时候,写好的程序需要打包成.exe文件才可以发给客户,那么今天我就来谈一谈,如何将一个写好的Python程序打包成exe文件! 首先,我们我们使用到的工具是python 3.7 和 Pyins ...
- Python项目打包成exe文件
这里我们使用pyinstaller这个软件即可,使用pip即可完美安装,在要打包的程序目录下打开cmd输入 pyinstaller -F 文件名.py 即可成功,运行成功后生成一个dict文件夹,东西 ...
- Python项目生成requirements.txt文件之pipreqs的使用
生成requirements.txt时使用pip freeze > requirements.txt会将环境下所有的安装包都进行生成,再进行安装的时候会全部安装很多没有的包.耗时耗力其实是不可取 ...
- pyinstaller使用-python项目转换成exe可执行文件
http://blog.csdn.net/pipisorry/article/details/50620122 Python不是每个人的计算机里面都有安装,当您写了一个好用的工具,需要一个standa ...
- python 项目部署virtualenv
安装virtualenv---------------------------------------- mac: pip3 install virtualenv ubuntu: apt instal ...
- Pyton项目打包成exe文件
Python项目打包成exe文件 1 系统环境 windows版本: Win7 64位 python环境:Anaconda python版本:3.6 64位 pyinstaller版本:3.5 1 安 ...
- 将Python项目打包成EXE可执行文件(单文件,多文件,包含图片)
解决 将Python项目打包成EXE可执行文件(单文件,多文件,包含图片) 1.当我们写了一个Python的项目时,特别是一个GUI项目,我们特备希望它能成为一个在Windows系统可执行的EXE文件 ...
- python 项目中包中__init__.py文件的作用
开发python项目时,我遇到了一个这样的现象,当我新建一个pythonpackage时,总会自动地生成一个空的__init__.py文件,因为是python新手,所以很不了解这个空文件的作用是什么, ...
随机推荐
- ModelSerializer 使用知识点_序列化和反序列化用法区别
1.ModelSerializer 如下 from api_test.errorCode.errorCode import Statusclass RelatedbSerializer(serial ...
- jodd cache实现缓存超时
public class JoddCache { private static final int CACHE_SIZE = 2; private final static Cache<Obje ...
- Spring Data Jpa (三)定义查询方法
本章详细讲解如何利用方法名定义查询方法(Defining Query Methods) (1)定义查询方法的配置方法 由于Spring JPA Repository的实现原理是采用动态代理的机制,所以 ...
- 二次封装axios,根据参数来实现多个请求多次拦截
1. 新建 axiosTool.js 文件,设置请求拦截和处理的逻辑 import Vue from 'vue' import axios from 'axios' //取消请求 let Cancel ...
- rbac权限组件整合到实际项目的全过程详述
rbac简介 项目的GitHub地址 欢迎Download&Fork&Star:https://github.com/Wanghongw/CombineRbac 另外,本文只简单介绍一 ...
- excel简单操作
百度网盘(npoi.dll): http://pan.baidu.com/s/14eJRw //先创建一个文件流,指向磁盘上的某个Excel文件 using (FileStream fsRead = ...
- Quartz安装包中的15个example
Welcome======= Welcome to the Quartz Examples directory. This directory contains 15 examples that sh ...
- Spring+hibernate 配置实例
转自:http://www.cnblogs.com/hongten/archive/2012/03/10/java_spring_hibernate.html 项目结构: http://www.cnb ...
- LeetCode All in One 题目讲解汇总(转...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通 ...
- Elasticsearch 安装head插件
一.简介 elasticsearch-head是一个界面化的集群操作和管理工具,可以对集群进行傻瓜式操作.你可以通过插件把它集成到es(首选方式),也可以安装成一个独立webapp. Elastics ...