cython把python编译成exe_使用Cython将py编译成.so文件

  • Post author:
  • Post category:python


#!/usr/bin/env python#-*- coding: utf-8 -*-#@File : build.py#@Author: Wade Cheung, EditBy BH liu#@Date : 2019/2/23#@Desc : 使用Cython.Build.cythonize将py编译成.so文件

importsysimportosimportshutilfrom distutils.core importsetupfrom Cython.Build importcythonize

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”filter_dir_set= {‘dist’, ‘build’, ‘data’, ‘test’, ‘orm\\data’}

except_files={__file__,’build.py’,’main.py’,’frozen_dir.py’,’libs\\time_it.py’,

}deffilter_file(file_name):if file_name.__contains__(currdir):

file_name= file_name.replace(currdir, ”)if file_name in except_files: #过滤文件

returnTrue

file_path= file_name.split(“\\”)if len(file_path) > 1:

file_dir= “”

for i in range(len(file_path)-1):

file_dir=os.path.join(file_dir, file_path[i])if file_dir infilter_dir_set:returnTruereturn file_path[0] infilter_dir_setdef getpy(basepath=os.path.abspath(‘.’), parentpath=”, name=”,

copyOther=False, delC=False):”””获取py文件的路径

:param basepath: 根路径

:param parentpath: 父路径

:param name: 文件/夹

:param copy: 是否copy其他文件

:return: py文件的迭代器”””fullpath=os.path.join(basepath, parentpath, name)for fname inos.listdir(fullpath):

ffile=os.path.join(fullpath, fname)if os.path.isdir(ffile) and fname != build_dir and not fname.startswith(‘.’):for f ingetpy(basepath, os.path.join(parentpath, name), fname,

copyOther, delC):yieldfelifos.path.isfile(ffile):

ext= os.path.splitext(fname)[1]#删除.c 临时文件

if ext == “.c”:ifdelC:

os.remove(ffile)elif not filter_file(ffile) and (ext not in (‘.pyc’, ‘.pyx’)and ext in (‘.py’, ‘.pyx’)and not fname.startswith(‘__’)):yieldos.path.join(parentpath, name, fname)elif copyOther and ext not in (‘.pyc’, ‘.pyx’): #复制其他文件到./build 目录下

dstdir =os.path.join(basepath, build_dir, parentpath, name)if notos.path.isdir(dstdir):

os.makedirs(dstdir)

shutil.copyfile(ffile, os.path.join(dstdir, fname))else:pass

#获取py列表

module_set = set(getpy(basepath=currdir, parentpath=parentpath))## 编译成.so文件

try:

setup(ext_modules=cythonize(module_set, language_level=3),

script_args=[“build_ext”, “-b”, build_dir, “-t”, build_tmp_dir])pass

exceptException as ex:print(“error!”, str(ex))else:#复制其他文件到./build 目录下

list(getpy(basepath=currdir, parentpath=parentpath, copyOther=True))#删除临时文件 ~

list(getpy(basepath=currdir, parentpath=parentpath, delC=True))ifos.path.exists(build_tmp_dir):

shutil.rmtree(build_tmp_dir)print(“Done !”)