""" 优化版打包脚本 - 加速启动时间 优化措施: 1. 延迟导入大型模块(QWebEngineView, InfluxDBClient) 2. 排除不需要的模块 3. 不使用 UPX 压缩 4. 优化 Python 字节码 """ import os import sys import shutil import subprocess def main(): # 检查是否安装了 PyInstaller try: import PyInstaller except ImportError: print("错误:未安装 PyInstaller") print("请运行: pip install pyinstaller") sys.exit(1) # 解析命令行参数 onedir = "--onedir" in sys.argv # 清理之前的构建 if os.path.exists("build"): shutil.rmtree("build") if os.path.exists("dist"): shutil.rmtree("dist") if os.path.exists("PCM_Viewer.spec"): os.remove("PCM_Viewer.spec") # 构建优化的 PyInstaller 命令 cmd = [ "pyinstaller", "--name=PCM_Viewer", "--windowed", # 不显示控制台窗口 "--onefile" if not onedir else "--onedir", # ========== 启动速度优化 ========== "--noupx", # 不使用 UPX 压缩(UPX 会增加启动时间) "--optimize=2", # Python 字节码优化级别(0-2,2 最高) # 排除不需要的大型模块(减少打包体积和启动时间) "--exclude-module=matplotlib", "--exclude-module=numpy", "--exclude-module=pandas", "--exclude-module=scipy", "--exclude-module=PIL", "--exclude-module=tkinter", "--exclude-module=PyQt5", # 排除 PyQt5(如果不需要) # 隐藏导入(延迟导入的模块) "--hidden-import=PyQt6.QtWebEngineWidgets", "--hidden-import=influxdb_client", "--hidden-import=influxdb_client.client", "--hidden-import=influxdb_client.client.write_api", "--hidden-import=influxdb_client.client.query_api", "--hidden-import=influxdb_wrapper", # 只收集必要的 PyQt6 模块(不收集全部,减少体积) "--collect-all=PyQt6.QtWebEngineWidgets", # WebEngine 需要完整收集 # 不收集其他大型库 "--collect-submodules=influxdb_client", # 只收集 influxdb_client 的子模块 "main.py" ] print("开始打包(优化版)...") print(f"模式: {'单文件' if not onedir else '文件夹'}") print(f"优化措施: 延迟导入、排除不需要的模块、不使用 UPX") print(f"命令: {' '.join(cmd)}") print() # 执行打包 result = subprocess.run(cmd, check=False) if result.returncode == 0: print("\n打包成功!") if not onedir: print("单文件位置: dist/PCM_Viewer.exe") print("\n优化说明:") print("1. 延迟导入 QWebEngineView 和 InfluxDBClient,减少启动时间") print("2. 排除了不需要的大型模块(matplotlib, numpy 等)") print("3. 不使用 UPX 压缩,避免解压时间") print("4. 首次运行会在 exe 同目录创建配置文件") else: print("文件夹位置: dist/PCM_Viewer/") print("可执行文件: dist/PCM_Viewer/PCM_Viewer.exe") else: print("\n打包失败!") sys.exit(1) if __name__ == "__main__": main()