思路是先将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. 更好的构建 Node 服务的工具

    更好的构建 Node 服务的工具 无论前端项目在打包后都发送给后台, 有时候自己想看看效果在运行 npm run build 后只是看到一个 build 文件夹,但是直接打开是无法浏览,因此需要开启一 ...

  2. [nginx] CORS配置多域名

    如下 server { listen 80; server_name www.your.com; root /data/web/www.your.com; access_log /var/log/ng ...

  3. Java equals 和 hashCode 的这几个问题可以说明白吗?

    前言 上一篇文章 如何妙用 Spring 数据绑定? ,灵魂追问 环节留下了一个有关 equals 和 hashcode 问题 .基础面试经常会碰到与之相关的问题,这不是一个复杂的问题,但很多朋友都苦 ...

  4. Spring MVC 同一个方法同时返回view或json

    https://blog.csdn.net/zzg1229059735/article/details/50854778 @RequestMapping(value = "/htmlorjs ...

  5. 运维自动化之ansible的安装与使用 转

    运维自动化之ansible的安装与使用 随着服务器数量的增长,我们需要一个批量工具去提高工作效率,之前用的是puppet,ansible的简单,适用让我眼前一亮,决定写一篇ansible从安装到基本配 ...

  6. 卡死浏览器使IPhone的自带safari打开重启的JS循环代码

    <html> <body> <script> var total=""; for (var i=0; i < 1000000; i++) ...

  7. 64位ubuntu下安装ia32-libs

    echo "deb http://archive.ubuntu.com/ubuntu/ raring main restricted universe multiverse" &g ...

  8. docker镜像和加速

    首先,需要明确一个问题:Mirror 与 Private Registry 有什么区别? Private Registry 是开发者或者企业自建的镜像存储库,通常用来保存企业内部的 Docker 镜像 ...

  9. spss中如何处理极端值、错误值

    spss中如何处理极端值.错误值 spss中录入数据以后,第一步不是去分析数据,而是要检验数据是不是有录入错误的,是不是有不合常理的数据,今天我们要做一个描述性统计,进而查看哪些数据是不合理的.下面是 ...

  10. Linux的远程桌面折腾指南

    因为实验服务器需要远程提供给研一童鞋使用,这两天折腾了一下Linux的远程桌面,在此记录总结一下.服务器系统为Lubuntu 16.04 远程登录到Linux 方案一:简单使用--x11vnc 单用户 ...