1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
| import os import sys import shutil import subprocess from pathlib import Path from datetime import datetime
class ApplicationBuilder: """应用程序构建器""" def __init__(self, app_name="AI办公工具套件"): self.app_name = app_name self.version = "1.0.0" self.build_dir = "build" self.dist_dir = "dist" self.spec_dir = "spec" self._create_directories() def _create_directories(self): """创建必要的目录""" directories = [self.build_dir, self.dist_dir, self.spec_dir, "assets", "config"] for directory in directories: Path(directory).mkdir(exist_ok=True) def clean_build(self): """清理构建文件""" print("🧹 清理构建文件...") for directory in [self.build_dir, self.dist_dir, self.spec_dir]: if Path(directory).exists(): shutil.rmtree(directory) self._create_directories() def create_assets(self): """创建资源文件""" print("🎨 创建资源文件...") config_content = { "app_name": self.app_name, "version": self.version, "build_date": datetime.now().isoformat(), "settings": { "max_file_size": 100 * 1024 * 1024, "allowed_extensions": [".pdf", ".docx", ".xlsx", ".pptx"], "enable_logging": True } } import json with open("config/settings.json", "w", encoding="utf-8") as f: json.dump(config_content, f, indent=2, ensure_ascii=False) def build_with_pyinstaller(self): """使用PyInstaller构建""" print("🚀 开始PyInstaller构建...") cmd = [ "pyinstaller", "--name", self.app_name, "--onefile", "--windowed", "--clean", "--noconfirm", "--distpath", self.dist_dir, "--workpath", self.build_dir, "--specpath", self.spec_dir, ] if sys.platform == "win32": cmd.extend([ "--icon", "assets/icon.ico", "--version-file", "version_info.txt" ]) elif sys.platform == "darwin": cmd.extend([ "--icon", "assets/icon.icns" ]) data_files = [ ("config/*.json", "config"), ("assets/*", "assets") ] for src, dest in data_files: cmd.extend(["--add-data", f"{src}{os.pathsep}{dest}"]) hidden_imports = [ "popdf", "python-office", "pypdf2", "docx", "openpyxl", "python-pptx", "PIL", "pandas", "numpy", "pyside6" ] for imp in hidden_imports: cmd.extend(["--hidden-import", imp]) cmd.append("office_tools_suite.py") try: result = subprocess.run(cmd, check=True, capture_output=True, text=True) print("✅ PyInstaller构建成功!") return True except subprocess.CalledProcessError as e: print(f"❌ PyInstaller构建失败: {e}") print(f"错误输出: {e.stderr}") return False def build_with_nuitka(self): """使用Nuitka构建(可选)""" print("⚡ 开始Nuitka构建...") cmd = [ "nuitka", "--standalone", "--onefile", "--windows-disable-console" if sys.platform == "win32" else "--macos-disable-console", f"--output-filename={self.app_name}", f"--output-dir={self.dist_dir}", "office_tools_suite.py" ] try: result = subprocess.run(cmd, check=True, capture_output=True, text=True) print("✅ Nuitka构建成功!") return True except subprocess.CalledProcessError as e: print(f"❌ Nuitka构建失败: {e}") return False def create_installer(self): """创建安装程序(Windows)""" if sys.platform != "win32": print("ℹ️ 安装程序创建仅支持Windows平台") return print("📦 创建安装程序...") iss_content = f""" #define MyAppName "{self.app_name}" #define MyAppVersion "{self.version}" #define MyAppPublisher "python-office" #define MyAppURL "https://github.com/程序员晚枫" #define MyAppExeName "{self.app_name}.exe"
[Setup] AppId={{{{MyAppName}}}} AppName={{#MyAppName}} AppVersion={{#MyAppVersion}} AppPublisher={{#MyAppPublisher}} AppPublisherURL={{#MyAppURL}} AppSupportURL={{#MyAppURL}} AppUpdatesURL={{#MyAppURL}} DefaultDirName={{autopf}}\\{{#MyAppName}} DefaultGroupName={{#MyAppName}} AllowNoIcons=yes OutputDir=installer OutputBaseFilename={{#MyAppName}}_Setup Compression=lzma SolidCompression=yes WizardStyle=modern
[Languages] Name: "english"; MessagesFile: "compiler:Default.isl" Name: "chinese"; MessagesFile: "compiler:Languages\\Chinese.isl"
[Tasks] Name: "desktopicon"; Description: "{{cm:CreateDesktopIcon}}"; GroupDescription: "{{cm:AdditionalIcons}}"; Flags: unchecked
[Files] Source: "dist\\{{#MyAppName}}.exe"; DestDir: "{{app}}"; Flags: ignoreversion Source: "assets\\*"; DestDir: "{{app}}\\assets"; Flags: ignoreversion recursesubdirs createallsubdirs Source: "config\\*"; DestDir: "{{app}}\\config"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons] Name: "{{group}}\\{{#MyAppName}}"; Filename: "{{app}}\\{{#MyAppExeName}}" Name: "{{autodesktop}}\\{{#MyAppName}}"; Filename: "{{app}}\\{{#MyAppExeName}}"; Tasks: desktopicon
[Run] Filename: "{{app}}\\{{#MyAppExeName}}"; Description: "{{cm:LaunchProgram,{{#StringChange(MyAppName, '&', '&&')}}}}"; Flags: nowait postinstall skipifsilent """ iss_file = "installer.iss" with open(iss_file, "w", encoding="utf-8") as f: f.write(iss_content) try: subprocess.run(["iscc", iss_file], check=True) print("✅ 安装程序创建成功!") except (subprocess.CalledProcessError, FileNotFoundError): print("ℹ️ 跳过安装程序创建(需要安装Inno Setup)") def analyze_build(self): """分析构建结果""" print("📊 分析构建结果...") exe_path = Path(self.dist_dir) / f"{self.app_name}.exe" if not exe_path.exists(): print("❌ 可执行文件未找到") return file_size = exe_path.stat().st_size / (1024 * 1024) print(f"📁 文件大小: {file_size:.2f} MB") try: import importlib.metadata dependencies = [] for dist in importlib.metadata.distributions(): dependencies.append(dist.metadata['Name']) print(f"📦 包含依赖: {len(dependencies)} 个包") except ImportError: print("ℹ️ 依赖分析需要Python 3.8+") def build(self, use_nuitka=False, create_installer=False): """执行完整构建流程""" print(f"🏗️ 开始构建 {self.app_name}...") self.clean_build() self.create_assets() if use_nuitka: success = self.build_with_nuitka() else: success = self.build_with_pyinstaller() if success: self.analyze_build() if create_installer: self.create_installer() print(f"🎉 {self.app_name} 构建完成!") print(f"📂 输出目录: {Path(self.dist_dir).absolute()}") else: print("❌ 构建失败,请检查错误信息")
if __name__ == "__main__": builder = ApplicationBuilder("AI办公工具套件") builder.build( use_nuitka=False, create_installer=True )
|