目的
將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 !")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/170796.html
標籤:Python
上一篇:python工程編譯成EXE
下一篇:Python集合:set
