#!/usr/bin/env python # -*- coding: utf-8 -*- """ 打包脚本 - 将 main.py 打包成 Windows EXE 文件 使用方法: python build_exe.py """ import os import sys import subprocess import shutil def check_python_version(): """检查 Python 版本""" if sys.version_info < (3, 7): print("[错误] 需要 Python 3.7 或更高版本") return False print(f"[信息] Python 版本: {sys.version}") return True def install_dependencies(): """安装依赖包""" print("\n[1/4] 检查并安装依赖包...") dependencies = [ 'redis>=4.0.0', 'oss2>=2.17.0', 'requests>=2.28.0', 'pyinstaller>=5.0.0', ] for dep in dependencies: print(f" 安装 {dep}...") result = subprocess.run( [sys.executable, '-m', 'pip', 'install', '--upgrade', dep], capture_output=True, text=True ) if result.returncode != 0: print(f"[错误] 安装 {dep} 失败: {result.stderr}") return False print("[成功] 所有依赖包已安装") return True def clean_build_files(): """清理之前的构建文件""" print("\n[2/4] 清理之前的构建文件...") dirs_to_remove = ['build', 'dist'] for dir_name in dirs_to_remove: if os.path.exists(dir_name): shutil.rmtree(dir_name) print(f" 已删除: {dir_name}") # 清理 __pycache__ 目录 for root, dirs, files in os.walk('.'): if '__pycache__' in dirs: pycache_path = os.path.join(root, '__pycache__') shutil.rmtree(pycache_path) print(f" 已删除: {pycache_path}") print("[成功] 清理完成") return True def build_exe(): """使用 PyInstaller 打包""" print("\n[3/4] 使用 PyInstaller 打包...") spec_file = 'build_exe.spec' if not os.path.exists(spec_file): print(f"[错误] 未找到配置文件: {spec_file}") return False result = subprocess.run( [sys.executable, '-m', 'PyInstaller', spec_file, '--clean', '--noconfirm'], capture_output=True, text=True ) if result.returncode != 0: print(f"[错误] 打包失败:") print(result.stderr) return False print("[成功] 打包完成") return True def show_result(): """显示打包结果""" print("\n" + "="*50) print("打包结果:") print("="*50) exe_path = os.path.join('dist', 'factory_sliceing.exe') if os.path.exists(exe_path): file_size = os.path.getsize(exe_path) / (1024 * 1024) # MB print(f"✓ EXE 文件位置: {exe_path}") print(f"✓ 文件大小: {file_size:.2f} MB") else: print(f"✗ 未找到 EXE 文件: {exe_path}") print("\n使用说明:") print(" 1. 将 dist/factory_sliceing.exe 复制到目标 Windows 机器") print(" 2. 在命令行中运行: factory_sliceing.exe --work-dir D:\\work") print("="*50) def main(): """主函数""" print("="*50) print("开始打包 factory_sliceing 为 Windows EXE") print("="*50) # 切换到脚本所在目录 script_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(script_dir) print(f"[信息] 工作目录: {script_dir}") # 检查 Python 版本 if not check_python_version(): return 1 # 安装依赖 if not install_dependencies(): return 1 # 清理构建文件 if not clean_build_files(): return 1 # 打包 if not build_exe(): return 1 # 显示结果 show_result() return 0 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: print("\n\n[中断] 用户取消操作") sys.exit(1) except Exception as e: print(f"\n[错误] 发生异常: {str(e)}") import traceback traceback.print_exc() sys.exit(1)