首页 > 编程语言 >python批量编译pyd并保持原有的目录结构

python批量编译pyd并保持原有的目录结构

时间:2022-10-13 10:45:33浏览次数:92  
标签:__ python os 编译 build parentpath path pyd dir

参考 https://blog.csdn.net/joyopirate/article/details/118609151

使用时,将文件放在项目的最外层的目录即可

#-* -coding: UTF-8 -* -
__author__ = 'Arvin'
__modifier__ = 'zy'
__modifier__ = 'zzh'

"""
执行前提:
    系统安装python-devel 和 gcc
    Python安装cython
编译某个文件夹:
    python py2so.py BigoModel
生成结果:
    目录 build 下
生成完成后:
    启动文件还需要py/pyc担当,须将启动的py/pyc拷贝到编译目录并删除so文件
    
zy修改:
   原程序在编译之后,所有文件夹里面的py文件编译得到的库文件全都放在build里面,而丧失了原来的目录架构,导致互相之间的调用出问题。
   这里简单增加一些语句,实现编译后的库文件保留原来的py文件的目录架构
   但是这样子做的话,需要一个个地编译。而不能批量传入,会比较慢。暂时只想到这个办法 

zzh修改
   增加去掉中间.cp38-win_amd64的功能
     
"""

import sys, os, shutil, time
from distutils.core import setup
from Cython.Build import cythonize

from distutils.extension import Extension

starttime = time.time()
setupfile = os.path.join(os.path.abspath('.'), __file__)

def getpy(basepath=os.path.abspath('.'), parentpath='', name='', build_dir="build", 
          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)
        # 假如是文件夹 而且 不是build文件夹 而且不是‘.’开头
        if os.path.isdir(ffile) and ffile != os.path.join(basepath, build_dir) and not fname.startswith('.'):
            # 递归调用
            for f in getpy(basepath, os.path.join(parentpath, name), fname, build_dir, excepts, copyOther, delC):
                yield f
        # 假如是文件
        elif os.path.isfile(ffile):
            # print("\t", basepath, parentpath, name, ffile)
            # 获取文件的后缀名
            ext = os.path.splitext(fname)[1]
            # 假如是c文件,而且是本次编译生成的(最后修改时间 > 本次编译的开始时间),且指定了要执行删除操作,就删除
            if ext == ".c":
                if delC and os.stat(ffile).st_mtime > starttime:
                    os.remove(ffile)
            # 假如 这个文件不是本文件,而且不是pyc、pyx文件
            elif ffile not in excepts and ext not in('.pyc', '.pyx'):
                # print("\t\t", basepath, parentpath, name, ffile)
                # 假如是py文件
                if ext in('.py', '.pyx') and not fname.startswith('__'):
                    yield os.path.join(parentpath, name, fname)
                # 假如需要复制
                elif copyOther:
                    print('copy---------')
                    # 目标文件夹为build_dir的目录源码目录
                    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))
                    print("------------", ffile, os.path.join(dstdir, fname))
        else:
            pass

if __name__ == "__main__":
    # 当前路径
    currdir = os.path.abspath('.')
    # 要编译的源代码文件夹
    parentpath = sys.argv[1] if len(sys.argv) > 1 else "."

    # currdir为源代码路径上一层, parentpath为源代码文件夹
    currdir, parentpath = os.path.split(currdir if parentpath == "." else os.path.abspath(parentpath))

    # 用来存放编译文件的build文件夹
    build_dir = os.path.join(parentpath, "build")
    build_tmp_dir = os.path.join(build_dir, "temp")
    print("start:", currdir, parentpath, build_dir)

    # cd到currdir, 也就是源代码文件夹的上一层
    os.chdir(currdir)

    try:
        #获取py列表
        module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile)))
        print("build these:", module_list)

        # 编译
        # setup(ext_modules=cythonize(module_list), script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
        for filePath in module_list:
            path, file = os.path.split(filePath)
            absPath = os.path.join(build_dir, path)
            # 假如路径不存在,创建路径
            if not os.path.isdir(absPath):
                os.makedirs(absPath)
            # 编译
            setup(ext_modules=cythonize(filePath), script_args=["build_ext", "-b", absPath, "-t", build_tmp_dir])

            # # 清理缓存文件夹
            # if os.path.exists(build_tmp_dir):
            #     shutil.rmtree(build_tmp_dir)


        # 将编译好的pyd文件拷贝指build文件路径中 这一句貌似没执行(因为原本就已经在build文件夹里面了)
        print("begin copy")
        module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), copyOther=True))

    except Exception as ex:
        print("error! ", ex)
    finally:
        print("cleaning...")
        # 清理生成的中间C文件
        module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), delC=True))

        # 清理缓存文件夹
        if os.path.exists(build_tmp_dir):
            shutil.rmtree(build_tmp_dir)

        # 去掉中间的拓展名
        for root, dirs, files in os.walk(currdir):
            for name in files:
                if name.endswith(".pyd"):
                    file_path = os.path.join(root, name)
                    filename = file_path.split('.cp')[0]
                    os.rename('%s.cp38-win_amd64.pyd' % (filename), '%s.pyd' % (filename))


    print("complete! time:", time.time()-starttime, 's')

标签:__,python,os,编译,build,parentpath,path,pyd,dir
From: https://www.cnblogs.com/cokefentas/p/16787325.html

相关文章

  • Python-arango部分资料
    ​​https://www.yht7.com/news/29900​​​​https://94e.cn/info/4027​​​​http://www.iis7.com/a/nr/0212674.html​​​​https://www.arangodb.com/tutorials/cn-tu......
  • (python)python 3.9 安装 robotframework-ride 因为 wxPython 失败
    1.正常安装方式1)安装robotframeworkpipinstallrobotframework2)安装robotframework-ridepipinstallrobotframework-ride  2.针对上述步骤1.2)的解......
  • python安装
    1.下载python​​https://www.python.org/downloads/release/python-352/​​2.安装依赖的包yuminstall-ybzip2-develncurses-develgdbm-developenssl-develreadline......
  • python in--总结
    “in”的存在使得python在操作可迭代对象时简单得多,这便是“in”存在的一个最大的好处1.用于判断(查找)元素是否在可迭代对象中(不包括生成器;但包括set集合,set不能迭代,但是也......
  • python 排序函数--sort()--sorted()
    python中有两种排序方法,list内置sort()方法或者python内置的全局sorted()方法区别为:sort()方法对list排序会修改list本身,不会返回新list。sort()只能对list进行排序。......
  • python调用caffe
    进入caffe/python路径下,或者将python路径添加到环境变量,输入:pythonimportcaffeimportsyscaffe_root='/home/program/caffe'sys.path.insert(0,caffe_root+'/python')......
  • python中调用编译好的caffe
    importsyscaffe_python='/home/x/l/Caffe/build/python'sys.path.insert(0,caffe_python)......
  • segmentation fault(core dumped)--编译caffe
    重新编译caffe的步骤:sudomakeclean;sudomakeall-j8;sudomaketest;sudomakeruntest;解决:重新编译caffe,要从makeclean开始一步步来编译,不要漏掉了makeclean.......
  • python requirements 相关
    python中通过requirements.txt来记录项目所有的依赖包及其版本号,以便在其他的环境中部署。如果在开发的时候升级了依赖包,记得更新此文件!pipfreeze>requirements.txt在其......
  • Python基础三【字典】
    1#字典,键-值对,{}表示;字典项不排序;可以用任意值做为键;2importoperator3importpprint4myCat={'size':'fat','color':'gray','disposition':'loud'}5print......