SpringBoot+Vue美食烹饪互动平台全解析:从数据库设计到前后端联调
2026/10/12 4:33:11
在日常开发中,我们有时会遇到这样的需求:
.py文件.py,就能自动还原所有源码本文将手把手教你实现一个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中:
核心技巧:把“文件系统”变成 Python 变量。
build_self_extract.py这个脚本负责“打包一切”。
# build_self_extract.pyfrompathlibimportPathimportjson 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={}forfileinSOURCE_DIR.rglob("*"):iffile.is_dir():continueiffile.suffixnotinINCLUDE_EXT:continueifany(partinEXCLUDE_DIRSforpartinfile.parts):continueiffile.nameinEXCLUDE_FILES:continuerel_path=file.relative_to(SOURCE_DIR)files_data[str(rel_path)]=file.read_text(encoding="utf-8",errors="ignore")# 生成自解压 pywithOUTPUT_PY.open("w",encoding="utf-8")asf: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}")project/ ├── main.py ├── config.json ├── utils/ │ └── helper.py ├── build_self_extract.pypython build_self_extract.py生成结果:
build/ └── self_extract.pyself_extract.pypython self_extract.py执行后生成:
extracted_source/ ├── main.py ├── config.json ├── utils/ │ └── helper.py source_code.zip🎉源码完整还原 + 自动压缩完成!
你可以在此基础上轻松扩展:
.exe(配合 PyInstaller)✅ 优点:
📌 适合人群:
如果你觉得这个方案有用,欢迎点赞 + 收藏 + 关注👍