使用Cython將py編譯成.so文件


目的

將python3代碼編譯成pyd文件,以保護代碼。(注,只能單個py文件生成單個pyd文件,windows下為pyd文件,linux下為so文件)

網上找到一篇相關的博文 使用Cython將py編譯成.so文件 ,從介紹、環境、注意事項、代碼步驟注釋得十分詳細,因為代碼不太符合自己的要求,因此基於該文代碼重新寫了一份代碼。

對比實現

代碼要求:

  1. 將所有需要生成的pyd文件復制到build目錄下(已有)
  2. 將所有其他文件復制到build目錄下(修改為所有不生成pyd的文件,原文只支持py文件)
  3. 忽略文件及文件夾,文件夾路徑支持多級目錄(新增文件夾,改寫忽略文件為相對路徑,所有路徑均為相對路徑)

代碼步驟(同):

  1.  獲取需要加密的py列表; 
  2.  cython先將py轉換為c代碼, 然后編譯c為.o及.so文件; 
  3.  復制其他文件到./build 目錄下;
  4.  刪除臨時文件

注意事項:

  1. __開頭文件不能生成pyd文件,會報錯
  2. 引入pyd報錯時可用py文件替換
  3. 編譯后使用pycharm打開build目錄作為根目錄,設置python解釋器,再編譯成exe文件
  4. 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 !")

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM