思路是先将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. Eclipse通过JDBC连接MySQL数据库的步骤(最原始的几个步骤)

    java可以兼容目前市面上所有类型的数据库,主要是因为提供了两个接口,一个用于连接目标数据库,一个用于向数据库中传输SQL命令. Connection接口——连接目标数据库: Statement  接 ...

  2. 【python 应用之四】提升 Python 运行性能的 7 个习惯

    大家都知道艺赛旗的 RPA 依赖于 python 语言.因此我们可以掌握一些技巧,可尽量提高 Python 程序性能,也可以避免不必要的资源浪费.1.使用局部变量 尽量使用局部变量代替全局变量:便于维 ...

  3. Spotlight_on_windows 安装和监控

    一.下载 1.下载并安装Spotlight_on_windows 2.填写注册码 Authorization Key:295713336449229168750 Site Message:Bergel ...

  4. Centos 建一个指定大小的文件夹

    1.使用ramdisklinux可以把一部分内存mount为分区使用,通常为称为ramdisk,分为ramdisk, ramfs, tmpfs.可以一条命令实现我们的需求:mount none tes ...

  5. 阶段3 1.Mybatis_12.Mybatis注解开发_4 mybatis注解开发CRUD的其他操作

    delete 51已经被删除掉了. 查询一个 findUserByName模糊查询 带百分号的情况 value这个参数是固定的 返回值为int类型的

  6. Linux下安装redis-4.0.10

    1.下载redis-4.0.10 在redis官网(https://redis.io/download)下载redis-4.0.10 2.将安装包上传至Linux服务器 在Linux服务器根目录下创建 ...

  7. SELECT-OPTIONS对象

    1. SELECT-OPTIONS基本语法及定义 SELECT-OPTIONS通常用于参照一数据库字为建立数据输入域,其定义对象命名长度不能超过8位,其产生的屏幕对象最大输入长度为18位,语法如下: ...

  8. Scratch少儿编程系列:(五)猜数字

    一.程序说明: 程序生成1-100之间的随机数,如56,小明在输入框中输入猜的数字.如输入80,提示“猜大了”,如输入45,则提示“猜小了”. 不超过5次猜中,则成功,否则失败. 二.程序的流程图 为 ...

  9. 应用安全 - CMS - vBulletin漏洞汇总

    SSV-15384 Date: 2004.11 漏洞类别: SQL 注入 SSV-15476 Date: 2005.2 漏洞类别: RCE SSV-15482 Date: 2005.2 类型: RCE ...

  10. python 封装dlib模型进行人脸识别系统的登录认证

    1.直接上干货 #!/usr/bin/python # -*- coding: utf-8 -*- import time import dlib import numpy as np class f ...