Python实现一键生成自解压源码文件并打包项目

作者:

文章目录
  • 我们将得到两个东西: build_self_extract.py构建脚本,负责扫描并打包源码 self_extract.py自解压脚本,运行后会: 还原所有源码到目录 自动生成 source_code.zip 运行体验如下: python self_extract.py 输出: ✅ 源代码已还原并压缩为 source_code.zip
  • 整体思路非常清晰: 遍历项目目录 按规则筛选需要的文件(.py / .json) 排除虚拟环境、构建目录等 将源码内容序列化为 JSON 生成一个新的 self_extract.py 在 self_extract.py 中: 写回所有文件 再打包成 zip 核心技巧:把“文件系统”变成 Python 变量。
  • 这个脚本负责“打包一切”。 # build_self_extract.py from pathlib import Path import json SOURCE_DIR = Path(“./”) OUTPUT_DIR = Path(“build”) OUTPUT_PY = OUTPUT_DIR / “self_extract.py” INCLUDE_EXT = {“.py”, “.json”} # 需要打包的源码类型 EXCLUDE_DIRS = { “.git”, “.venv”, “venv”, “__pycache__”, “.history”, “build” } EXCLUDE_FILES = { “self_extract.py”, “build_self_extract.py”, “111.py” } OUTPUT_DIR.mkdir(exist_ok=True) files_data = {} for file in SOURCE_DIR.rglob(“*”): if file.is_dir(): continue if file.suffix not in INCLUDE_EXT: continue if any(part in EXCLUDE_DIRS for part in file.parts): continue if file.name in EXCLUDE_FILES: continue rel_path = file.relative_to(SOURCE_DIR) files_data[str(rel_path)] = file.read_text( encoding=”utf-8″, errors=”ignore” ) # 生成自解压 py with OUTPUT_PY.open(“w”, encoding=”utf-8″) as f: f.write( f”'””” 🚀 自解压源码文件 运行后将还原所有源代码并生成 source_code.zip “”” from pathlib import Path import zipfile import json FILES = json.loads({json.dumps(json.dumps(files_data, ensure_ascii=False))}) BASE_DIR = Path(“extracted_source”) ZIP_NAME = “source_code.zip” def main(): BASE_DIR.mkdir(exist_ok=True) # 写回所有文件 for path, content in FILES.items(): file_path = BASE_DIR / path file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(content, encoding=”utf-8″, errors=”replace”) # 打包为 zip with zipfile.ZipFile(ZIP_NAME, “w”, zipfile.ZIP_DEFLATED) as zf: for file in BASE_DIR.rglob(“*”): if file.is_file(): zf.write(file, arcname=file.relative_to(BASE_DIR)) print(“✅ 源代码已还原并压缩为”, ZIP_NAME) if __name__ == “__main__”: main() ”’ ) print(f”✅ 已生成自解压文件: {OUTPUT_PY}”)
  • 1.假设你的项目结构如下 project/├── main.py├── config.json├── utils/│   └── helper.py├── build_self_extract.py 2.执行构建脚本 python build_self_extract.py 生成结果: build/└── self_extract.py 3.分发或运行self_extract.py python self_extract.py 执行后生成: extracted_source/├── main.py├── config.json├── utils/│   └── helper.py source_code.zip 源码完整还原 + 自动压缩完成!
  • 你可以在此基础上轻松扩展: 给源码加密(base64 / AES) 增加版本号、作者信息 加 CLI 参数(如指定输出目录) 打包为 .exe(配合 PyInstaller) 通过 HTTP / API 动态释放
  • 优点: 单文件分发 无需额外依赖 代码可读、可控 非常适合内部工具和 Demo 适合人群: Python 工具作者 教学 / 培训 内部源码交付 自动化工程师 到此这篇关于Python实现一键生成自解压源码文件并打包项目的文章就介绍到这了,更多相关Python生成自解压源码内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: Python将源码打包成.whl文件的完整指南 python将依赖和源码打包在一起的方法 python实现rar解压和压缩的方法(附源码) 三步快速实现Python解包EXE文件获取源码的完整教学
  • 目录
    • 最终效果
    • 实现思路
    • 构建脚本:build_self_extract.py
    • 使用 Demo(完整流程)
    • 可扩展方向(进阶玩法)
    • 总结

    在日常开发中,我们有时会遇到这样的需求:

    • 想把一个项目源码打包成单个 .py 文件
    • 对方只需要运行这个 .py,就能自动还原所有源码
    • 同时还能生成一个 zip 压缩包,方便分发或存档

    本文将手把手教你实现一个 Python 自解压源码方案,非常适合:

    • 内部源码交付
    • Demo 示例分发
    • 离线代码传输
    • 教学或工具型项目发布

    我们将得到两个东西:

    build_self_extract.py构建脚本,负责扫描并打包源码

    self_extract.py自解压脚本,运行后会:

    • 还原所有源码到目录
    • 自动生成 source_code.zip

    运行体验如下:

    python self_extract.py
    

    输出:

    ✅ 源代码已还原并压缩为 source_code.zip

    整体思路非常清晰:

    遍历项目目录

    按规则筛选需要的文件(.py / .json

    排除虚拟环境、构建目录等

    将源码内容序列化为 JSON

    生成一个新的 self_extract.py

    self_extract.py 中:

    • 写回所有文件
    • 再打包成 zip

    核心技巧:把“文件系统”变成 Python 变量。

    这个脚本负责“打包一切”。

    # build_self_extract.py
    from pathlib import Path
    import json
    
    SOURCE_DIR = Path("./")
    OUTPUT_DIR = Path("build")
    OUTPUT_PY = OUTPUT_DIR / "self_extract.py"
    
    INCLUDE_EXT = {".py", ".json"}  # 需要打包的源码类型
    EXCLUDE_DIRS = {
        ".git", ".venv", "venv", "__pycache__", ".history", "build"
    }
    EXCLUDE_FILES = {
        "self_extract.py", "build_self_extract.py", "111.py"
    }
    
    OUTPUT_DIR.mkdir(exist_ok=True)
    
    files_data = {}
    
    for file in SOURCE_DIR.rglob("*"):
        if file.is_dir():
            continue
    
        if file.suffix not in INCLUDE_EXT:
            continue
    
        if any(part in EXCLUDE_DIRS for part in file.parts):
            continue
    
        if file.name in EXCLUDE_FILES:
            continue
    
        rel_path = file.relative_to(SOURCE_DIR)
        files_data[str(rel_path)] = file.read_text(
            encoding="utf-8", errors="ignore"
        )
    
    # 生成自解压 py
    with OUTPUT_PY.open("w", encoding="utf-8") as f:
        f.write(
            f'''"""
    🚀 自解压源码文件
    运行后将还原所有源代码并生成 source_code.zip
    """
    
    from pathlib import Path
    import zipfile
    import json
    
    FILES = json.loads({json.dumps(json.dumps(files_data, ensure_ascii=False))})
    
    BASE_DIR = Path("extracted_source")
    ZIP_NAME = "source_code.zip"
    
    def main():
        BASE_DIR.mkdir(exist_ok=True)
    
        # 写回所有文件
        for path, content in FILES.items():
            file_path = BASE_DIR / path
            file_path.parent.mkdir(parents=True, exist_ok=True)
            file_path.write_text(content, encoding="utf-8", errors="replace")
    
        # 打包为 zip
        with zipfile.ZipFile(ZIP_NAME, "w", zipfile.ZIP_DEFLATED) as zf:
            for file in BASE_DIR.rglob("*"):
                if file.is_file():
                    zf.write(file, arcname=file.relative_to(BASE_DIR))
    
        print("✅ 源代码已还原并压缩为", ZIP_NAME)
    
    if __name__ == "__main__":
        main()
    '''
        )
    
    print(f"✅ 已生成自解压文件: {OUTPUT_PY}")
    

    1.假设你的项目结构如下

    project/
    ├── main.py
    ├── config.json
    ├── utils/
    │   └── helper.py
    ├── build_self_extract.py

    2.执行构建脚本

    python build_self_extract.py
    

    生成结果:

    build/
    └── self_extract.py

    3.分发或运行self_extract.py

    python self_extract.py
    

    执行后生成:

    extracted_source/
    ├── main.py
    ├── config.json
    ├── utils/
    │   └── helper.py

    source_code.zip

    源码完整还原 + 自动压缩完成!

    你可以在此基础上轻松扩展:

    • 给源码加密(base64 / AES)
    • 增加版本号、作者信息
    • 加 CLI 参数(如指定输出目录)
    • 打包为 .exe(配合 PyInstaller)
    • 通过 HTTP / API 动态释放

    优点:

    • 单文件分发
    • 无需额外依赖
    • 代码可读、可控
    • 非常适合内部工具和 Demo

    适合人群:

    • Python 工具作者
    • 教学 / 培训
    • 内部源码交付
    • 自动化工程师

    到此这篇关于Python实现一键生成自解压源码文件并打包项目的文章就介绍到这了,更多相关Python生成自解压源码内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • Python将源码打包成.whl文件的完整指南
    • python将依赖和源码打包在一起的方法
    • python实现rar解压和压缩的方法(附源码)
    • 三步快速实现Python解包EXE文件获取源码的完整教学

    站内搜索