python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python生成自解压源码

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

作者:weixin_46244623

这篇文章主要为大家详细介绍了一个Python自解压源码方案,可将项目源码打包成单个.py文件,方便分发和存档,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下

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

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

最终效果

我们将得到两个东西:

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

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

运行体验如下:

python self_extract.py

输出:

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

实现思路

整体思路非常清晰:

遍历项目目录

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

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

将源码内容序列化为 JSON

生成一个新的 self_extract.py

self_extract.py 中:

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

构建脚本:build_self_extract.py

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

# 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}")

使用 Demo(完整流程)

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

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

可扩展方向(进阶玩法)

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

总结

优点:

适合人群:

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

您可能感兴趣的文章:
阅读全文