思路是先将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. Prometheus 后续杂记

    在后续prometheus的使用中遇到的一些问题我会在此记录 搭建初期几个问题 rule.yml中对每条告警加上主机名? 要在告警通知中加上故障机器主机名不能从prometheus的采集监控项数据中的 ...

  2. 快速沃尔变换 FWT

    P4717 [模板]快速沃尔什变换 #include<bits/stdc++.h> using namespace std; #define int long long #define s ...

  3. Oracle JET mobile 入门使用

    Oracle JET 框架能开发 window, Android, ios 的 WebApp .主要使用 Codova 来进行开发. 简单使用 Oracle JET 开发 Android webapp ...

  4. 算法中Amortised time的理解

    ref:http://stackoverflow.com/questions/200384/constant-amortized-time 如果非要翻译成中文,我觉得摊算时间或均摊时间(注意,它和平均 ...

  5. java应用cpu使用率过高问题排查

    ---------------------------------------linux下如何定位代码问题------------------------------- 1.先通过top命令找到消耗c ...

  6. linux可用的跨平台C# .net standard2.0 写的高性能socket框架

    能在window(IOCP)/linux(epoll)运行,基于C# .net standard2.0 写的socket框架,可使用于.net Framework/dotnet core程序集,.使用 ...

  7. QBXT Day 5图论相关

    图论是NOIP的一个非常重要的考点,换句话说,没有图论,NOIP的考纲就得少一大半(虽然很NOIP没有考纲) 图论这玩意吧,和数论一样是非常变态的东西,知识点又多又杂,但是好在一个事,他比较直观比较好 ...

  8. CentOS7配置静态IP中NM_CONTROLLED不要设置为NO

    这个是网络管理的,之前一直是把这个选项设置为NO,然后在CentOS其中,每次重启网络服务都会失败,后来把这个设为YES就可以了.

  9. 关于自定义 List集合排序的方法!

    大致流程: 排序是用到排序的接口Comparator<T>你要先建一个类实现比较器Comparator //大致流程public class StuComp implements Comp ...

  10. tuple用法

    1 tuple中的元素可以直接赋给相同个数的变量 tup1 = ('asfa',234) p, q = tup1 print(p) print(q) # asfa # 参考:https://www.r ...