目的
将python3代码编译成pyd文件,以保护代码。(注,只能单个py文件生成单个pyd文件,windows下为pyd文件,linux下为so文件)
网上找到一篇相关的博文 使用Cython将py编译成.so文件 ,从介绍、环境、注意事项、代码步骤注释得十分详细,因为代码不太符合自己的要求,因此基于该文代码重新写了一份代码。
对比实现
代码要求:
- 将所有需要生成的pyd文件复制到build目录下(已有)
- 将所有其他文件复制到build目录下(修改为所有不生成pyd的文件,原文只支持py文件)
- 忽略文件及文件夹,文件夹路径支持多级目录(新增文件夹,改写忽略文件为相对路径,所有路径均为相对路径)
代码步骤(同):
- 获取需要加密的py列表;
- cython先将py转换为c代码, 然后编译c为.o及.so文件;
- 复制其他文件到./build 目录下;
- 删除临时文件
注意事项:
- __开头文件不能生成pyd文件,会报错
- 引入pyd报错时可用py文件替换
- 编译后使用pycharm打开build目录作为根目录,设置python解释器,再编译成exe文件
-
source_items = (item for item in source_items) 这种写法有问题,生成器后的变量名应与之前的变量名不同,否则报错(ValueError: generator already executing),该例可以改为
target_items = (item for item in source_items)
源代码(放在项目根目录下):
#!/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文件 import sys import os import shutil from distutils.core import setup from Cython.Build import cythonize 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', } def filter_file(file_name): if file_name.__contains__(currdir): file_name = file_name.replace(currdir, '') if file_name in except_files: # 过滤文件 return True 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 in filter_dir_set: return True return file_path[0] in filter_dir_set def 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 in os.listdir(fullpath): ffile = os.path.join(fullpath, fname) if os.path.isdir(ffile) and fname != build_dir and not fname.startswith('.'): for f in getpy(basepath, os.path.join(parentpath, name), fname, copyOther, delC): yield f elif os.path.isfile(ffile): ext = os.path.splitext(fname)[1] # 删除.c 临时文件 if ext == ".c": if delC: os.remove(ffile) elif not filter_file(ffile) and (ext not in ('.pyc', '.pyx') and ext in ('.py', '.pyx') and not fname.startswith('__')): yield os.path.join(parentpath, name, fname) elif copyOther and ext not in ('.pyc', '.pyx'): # 复制其他文件到./build 目录下 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_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 except Exception as ex: print("error! ", str(ex)) else: # 复制其他文件到./build 目录下 list(getpy(basepath=currdir, parentpath=parentpath, copyOther=True)) # 删除临时文件 ~ list(getpy(basepath=currdir, parentpath=parentpath, delC=True)) if os.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir) print("Done !")