在日常开发中,我们有时会遇到这样的需求:
- 想把一个项目源码打包成单个
.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
这个脚本负责“打包一切”。
# 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
源码完整还原 + 自动压缩完成!
可扩展方向(进阶玩法)
你可以在此基础上轻松扩展:
- 给源码加密(base64 / aes)
- 增加版本号、作者信息
- 加 cli 参数(如指定输出目录)
- 打包为
.exe(配合 pyinstaller) - 通过 http / api 动态释放
总结
优点:
- 单文件分发
- 无需额外依赖
- 代码可读、可控
- 非常适合内部工具和 demo
适合人群:
- python 工具作者
- 教学 / 培训
- 内部源码交付
- 自动化工程师
到此这篇关于python实现一键生成自解压源码文件并打包项目的文章就介绍到这了,更多相关python生成自解压源码内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论