python代码打包加密

复制代码
# -*- coding: utf-8 -*-

"""
@author: Mr_zhang
@software: PyCharm
@file: build.py
@time: 2021/2/8 21:13
"""

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

ROOT_PATH = os.path.abspath('.')
PROJECT_NAME = ROOT_PATH.split('/')[-1]

# Ignore
EXCEPT_FILES = {
    'build.py'
}

# Only copy
IGNORE_FILES = {
    'manage.py',
}

IGNORE_HIDE_FILES = ('.env', '.env_example', '.env_dev')

PY_FILE_EXCEPT_SUF = ('.pyc', '.pyx')
PY_FILE_SUF = ('.py',)
PATTERN = re.compile(r'^\d+')


def ls(_dir=''):
    """Return all relative path under the current folder."""
    dir_path = os.path.join(ROOT_PATH, _dir)
    for filename in os.listdir(dir_path):
        absolute_file_path = os.path.join(dir_path, filename)
        file_path = os.path.join(_dir, filename)
        if filename.startswith('.') and filename not in IGNORE_HIDE_FILES:
            continue
        if os.path.isdir(absolute_file_path) and not filename.startswith('__'):
            for file in ls(file_path):
                yield file
        else:
            yield file_path


def copy_ignore(dist='dist'):
    """Copy exclude files"""
    files = ls()
    for file in files:
        file_arr = file.split('/')
        if file_arr[0] == dist:
            continue
        suffix = os.path.splitext(file)[1]
        if not suffix and file not in IGNORE_HIDE_FILES:
            continue
        if file_arr[0] not in IGNORE_FILES and file not in IGNORE_FILES:
            if suffix in PY_FILE_EXCEPT_SUF:
                continue
            elif suffix in PY_FILE_SUF:
                if not PATTERN.findall(file.split('/')[-1]):
                    continue
        src = os.path.join(ROOT_PATH, file)
        dst = os.path.join(ROOT_PATH, os.path.join(dist, file.replace(ROOT_PATH, '', 1)))
        _dir = '/'.join(dst.split('/')[:-1])
        if not os.path.exists(_dir):
            os.makedirs(_dir)
        shutil.copyfile(src, dst)


def build(dist='dist'):
    """py -> c -> so"""
    start = time.time()
    files = list(ls())
    module_list = list()
    exclude_list = list()
    for file in files:
        if file in EXCEPT_FILES or file in IGNORE_FILES:
            continue
        
        suffix = os.path.splitext(file)[1]
        if not suffix:
            continue
        elif suffix in PY_FILE_EXCEPT_SUF:
            continue
        elif suffix in PY_FILE_SUF:
            if not PATTERN.findall(file.split('/')[-1]):
                module_list.append(file)
            else:
                exclude_list.append(file)
    dist = os.path.join('.', dist)
    dist_temp = os.path.join(dist, 'temp')
    try:
        setup(ext_modules=cythonize(module_list, exclude=exclude_list, language_level="3", exclude_failures=True),
              script_args=["build_ext", "-b", dist, "-t", dist_temp])
    except Exception as e:
        print('Error: ', e)
        if os.path.exists(dist_temp):
            shutil.rmtree(dist_temp)
        for file in ls():
            if not file.endswith('.c'):
                continue
            os.remove(os.path.join(ROOT_PATH, file))
        return
    
    if os.path.exists(dist_temp):
        shutil.rmtree(dist_temp)
    for file in ls():
        if not file.endswith('.c'):
            continue
        os.remove(os.path.join(ROOT_PATH, file))
    
    copy_ignore()
    end = time.time()
    print('Complete, %.2fs !' % (end - start))


if __name__ == '__main__':
    build()
    # copy_ignore()
    # for file in ls():
    #     if not file.endswith('.c'):
    #         continue
    #     os.remove(os.path.join(ROOT_PATH, file))
复制代码

 

posted @   一石数字欠我15w!!!  阅读(507)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
历史上的今天:
2018-01-19 存储库-MongoDB简单的操作
2018-01-19 解析库-beautifulsoup模块
点击右上角即可分享
微信分享提示