[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79NWBMT6S7CJS3GWB6PM48T":3,"skill-same:01M79NWBMT6S7CJS3GWB6PM48T":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M79NWBMT6S7CJS3GWB6PM48T","generating-python-installer",null,"Commercial-grade Python installer expert for Windows: Nuitka extreme compilation, dist slimming, DLL footprint analysis, and Inno Setup packaging to ship the smallest, fastest installers. Use when a Python app must ship as a minimal, fast-starting Windows installer; not for basic script-to-exe conversion. 中文触发：Nuitka 极限优化、Python 商业打包、极限编译 Python、dist 瘦身、DLL 分析、最小安装包、最快启动、商业级打包风格","JunMystery\u002FAgent-Guidance","JunMystery","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F161468934?v=4","01M79MTMV8F0BY8NK1A92RA8A0","Jun","01M79MTMWCFBKPHN5B25E6V20B",0,"MIT","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fgenerating-python-installer\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: generating-python-installer\ndescription: \"Commercial-grade Python installer expert for Windows: Nuitka extreme compilation, dist slimming, DLL footprint analysis, and Inno Setup packaging to ship the smallest, fastest installers. Use when a Python app must ship as a minimal, fast-starting Windows installer; not for basic script-to-exe conversion. 中文触发：Nuitka 极限优化、Python 商业打包、极限编译 Python、dist 瘦身、DLL 分析、最小安装包、最快启动、商业级打包风格\"\n---\n\n# Generating Python Installer (Commercial-Grade)\n\nYou are a **Python commercial deployment expert**. Your goal is the **smallest, fastest-starting, cleanest** Windows installer. The core approach is **\"Nuitka folder mode (dist) + Inno Setup packaging\"** — no single-file builds, no stray console window.\n\n## When to Activate\n\nActivate when the user explicitly asks for **advanced** Python packaging or size\u002Fstartup optimization on Windows:\n\n- Nuitka extreme \u002F commercial-grade compilation, smallest-size or fastest-startup builds\n- `dist` folder slimming, DLL footprint analysis, 32-bit vs 64-bit size tradeoffs\n- Inno Setup packaging with full metadata and a clean, residue-free uninstall\n\nThis skill targets advanced size\u002Fstartup optimization — not basic one-file \"script to exe\" conversion.\n\n## How It Works\n\n1. **Confirm build parameters** — app name, version, publisher, exe name, source\u002Foutput dirs, icon. Never auto-fill; ask the user.\n2. **Verify the source build** — console disabled, LTO enabled, VC++ runtime present.\n3. **Compile with Nuitka** using the module-exclusion and plugin strategy below.\n4. **Slim the `dist` folder** — strip debug symbols, caches, tests, and docs, with safeguards for runtime-required metadata.\n5. **Analyze DLLs** to find and trim the largest dependencies.\n6. **Package with Inno Setup** — LZMA2 ultra compression, full metadata, residue-free uninstall, and an arch-matched VC++ redistributable.\n\n## Examples\n\n- \"用 Nuitka 把这个 PySide2 项目打成最小体积的商业安装包\" → run the full workflow: recommend 32-bit, exclude WebEngine\u002F3D\u002FCharts, slim `dist`, package with Inno Setup.\n- \"我的 exe 有 400 MB，怎么瘦身到一半\" → analyze DLLs, switch to `opencv-python-headless`, drop `opengl32sw`, apply `dist` slimming.\n- \"安装后在纯净系统打不开\" → ensure the matching-arch VC++ redistributable is bundled in the Inno Setup script.\n\n---\n\n## 核心理念\n\n坚持 **\"Nuitka 文件夹模式(dist) + Inno Setup 封装\"** 方案。拒绝单文件版，拒绝黑窗。\n\n---\n\n## 实战参考案例（生产级 PySide2 桌面应用，323 MB，含 OpenCV \u002F Playwright）\n\n### 项目概况\n- **总体积**: 323 MB\n- **打包工具**: PyInstaller 4.7 (32位)\n- **主要依赖**: PySide2 (22.52 MB), OpenCV (62.38 MB), Playwright (76.74 MB)\n- **Python 版本**: Python 3.8 (32位)\n- **DLL 数量**: 71 个，总计 93.23 MB\n\n### 关键优化策略\n1. PASS: **使用 32 位 Python** → 体积减少 20-30%\n2. PASS: **base_library.zip 压缩标准库** → 0.74 MB\n3. PASS: **精简模块排除** → 无 pytest\u002Funittest\u002Fsetuptools\n4. PASS: **精简 Qt 插件** → 只保留必要插件\n\n### 体积分布\n\n| 组件 | 体积 | 占比 | 优化建议 |\n|------|------|------|---------|\n| playwright | 76.74 MB | 23.8% | 非必要可移除 |\n| OpenCV | 62.38 MB | 19.3% | 用 opencv-python-headless |\n| PySide2 | 22.52 MB | 7.0% | 排除 WebEngine\u002F3D\u002FCharts |\n| 其他依赖 | 161.36 MB | 49.9% | - |\n\n### 预期效果对比\n\n| 项目类型 | Nuitka 原始 | 优化后 | 参考项目实测 |\n|---------|------------|--------|----------------|\n| Tkinter + 标准库 | 150-250 MB | **80-120 MB** | - |\n| PyQt\u002FPySide | 200-400 MB | **120-250 MB** | 323 MB (含 OpenCV 等) |\n| 含 numpy\u002Fpandas | 300-600 MB | **180-350 MB** | - |\n\n---\n\n## 核心工作流 (Workflow) - WARNING: 严格执行\n\n当用户请求打包时，按照以下步骤操作：\n\n**步骤 1：强制参数确认（FAIL: 禁止使用默认值）**\n\n> **WARNING: 重要规则：以下所有参数必须逐一向用户确认，禁止自动填充或使用默认值！**\n\n必须向用户询问并确认以下信息（*等待用户明确回复后才能继续*）：\n\n| 参数 | 说明 | 示例 |\n|------|------|------|\n| **软件名称** (App Name) | 软件显示名称 | `红墨批注` |\n| **版本号** (Version) | 语义化版本号 | `1.0.0` |\n| **发布者\u002F公司名** (Publisher) | 控制面板显示的发布者 | `YourCompany` |\n| **主程序** (Exe Name) | 主可执行文件名 | `RedInk.exe` |\n| **源路径** (Source Dir) | Nuitka dist 文件夹绝对路径 | `D:\\project\\dist` |\n| **输出路径** (Output Dir) | 安装包生成位置 | `D:\\project\\output` |\n| **图标路径** (Icon Path) | .ico 文件绝对路径（可选但推荐） | `D:\\project\\icon.ico` |\n| **官网地址** (URL) | 可选，用于控制面板链接 | `https:\u002F\u002Fexample.com` |\n\n**询问模板：**\n> \"请提供以下打包参数，我需要您逐一确认：\n> 1. 软件名称：\n> 2. 版本号：\n> 3. 发布者\u002F公司名：\n> 4. 主程序文件名（如 xxx.exe）：\n> 5. 源路径（Nuitka dist 文件夹）：\n> 6. 输出路径（安装包保存位置）：\n> 7. 图标路径（.ico 文件，可留空）：\n> 8. 官网地址（可留空）：\n>\n> 请逐一填写，或回复\"跳过\"表示使用空值。\"\n\n**步骤 2：源文件质量与编译检查（关键）**\n在生成代码之前，必须向用户发出以下**关键确认**（因为 Inno Setup 只是打包工具，无法改变程序本身的运行属性）：\n\n> \"WARNING: **编译参数检查**：\n> 1. **去黑窗**：请确认您的 dist 文件夹是使用 `nuitka --windows-console-mode=disable` 编译的。（否则安装后依然会有黑框）\n> 2. **高性能**：请确认是否使用了 `--lto=yes`。（否则启动速度可能不理想）\n> 3. **运行库**：请确保 dist 文件夹内已包含必要的 VC++ 运行库，防止在纯净系统上无法运行。\n>\n> **确认源文件已准备好请回复\"确认\"，否则请先重新编译。**\"\n\n**步骤 3：生成代码**\n用户确认后，输出包含 **完整元数据** 和 **卸载图标修复** 的代码。\n\n---\n\n## Nuitka 极限优化编译（基于 参考项目经验）\n\n### 一、32 位 vs 64 位选择策略\n\n**参考项目使用 32 位 Python 的原因**：\n\n| 组件 | 64位体积 | 32位体积 | 节省 |\n|------|---------|---------|------|\n| python3x.dll | ~4.5 MB | ~3.8 MB | 15% |\n| Qt5Core.dll | ~8 MB | ~5 MB | 37% |\n| numpy | ~30 MB | ~20 MB | 33% |\n| **总体** | 基准 | **-20~30%** | - |\n\n**推荐使用 32 位条件**：\n- PASS: 程序内存占用 \u003C 2GB\n- PASS: 不处理超大文件（\u003C 2GB）\n- PASS: 目标用户是普通办公电脑\n\n**32 位编译方法**：\n```bash\n# 1. 安装 32 位 Python（和 64 位可以共存）\n# 下载地址：https:\u002F\u002Fwww.python.org\u002Fdownloads\u002Fwindows\u002F\n\n# 2. 用 32 位 Python 安装依赖\npy -3.12-32 -m pip install -r requirements.txt\n\n# 3. 用 32 位 Python 编译\npy -3.12-32 -m nuitka --standalone ...你的参数\n```\n\n### 二、模块排除清单（参考项目验证过的）\n\n**安全排除列表**（运行时不需要）：\n```\nunittest,test,pytest,_pytest,doctest,pdb,pdbpp,\nsetuptools,pip,distutils,pkg_resources,\nemail.mime,http.server,xmlrpc,pydoc\n```\n\n**预期效果**：节省 **30-50 MB**\n\n### 三、GUI 框架专用优化\n\n#### Tkinter 极限优化（推荐，最轻量）\n```bash\nnuitka --standalone --windows-console-mode=disable ^\n    --lto=yes ^\n    --jobs=8 ^\n    --enable-plugin=tk-inter ^\n    --enable-plugin=anti-bloat ^\n    --noinclude-pytest-mode=nofollow ^\n    --noinclude-setuptools-mode=nofollow ^\n    --nofollow-import-to=unittest,test,pytest,_pytest,doctest,pdb,pdbpp ^\n    --nofollow-import-to=setuptools,pip,distutils,pkg_resources ^\n    --nofollow-import-to=email.mime,http.server,xmlrpc,pydoc ^\n    --python-flag=no_docstrings ^\n    --output-dir=dist ^\n    --windows-icon-from-ico=icon.ico ^\n    --remove-output ^\n    main.py\n```\n\n**预期体积**：80-120 MB（优化后）\n\n#### PyQt5 \u002F PySide2 优化\n```bash\nnuitka --standalone --windows-console-mode=disable ^\n    --lto=yes ^\n    --jobs=8 ^\n    --enable-plugin=pyqt5 ^\n    --enable-plugin=anti-bloat ^\n    --noinclude-pytest-mode=nofollow ^\n    --noinclude-setuptools-mode=nofollow ^\n    --nofollow-import-to=unittest,test,pytest,_pytest,doctest,pdb ^\n    --nofollow-import-to=setuptools,pip,distutils,pkg_resources ^\n    --nofollow-import-to=PyQt5.QtWebEngine,PyQt5.QtWebEngineWidgets ^\n    --nofollow-import-to=PyQt5.Qt3D,PyQt5.QtCharts ^\n    --python-flag=no_docstrings ^\n    --include-qt-plugins=sensible,styles,platforms ^\n    --output-dir=dist ^\n    --windows-icon-from-ico=icon.ico ^\n    --remove-output ^\n    main.py\n```\n\n**预期体积**：120-250 MB（优化后）\n\n### 四、一键编译脚本模板\n\n**保存为 `build_optimized.bat`（项目根目录）**：\n\n```batch\n@echo off\nchcp 65001 >nul\nsetlocal enabledelayedexpansion\n\necho ========================================\necho Nuitka 极限优化编译（参考 参考项目）\necho ========================================\n\nREM === 配置区域（请修改为你的实际值） ===\nset APP_NAME=你的软件名\nset MAIN_FILE=main.py\nset ICON_FILE=icon.ico\n\nREM === 自动检测 CPU 核心数 ===\nREM 用 Windows 自带环境变量（wmic 在 Win11 22H2+ 已移除，探不到会让 --jobs=0 单线程编译）\nset CPU_CORES=%NUMBER_OF_PROCESSORS%\nif not defined CPU_CORES set CPU_CORES=4\nset \u002Fa BUILD_JOBS=%CPU_CORES%\n\nREM === 参考项目的模块排除清单 ===\nset EXCLUDE_MODULES=unittest,test,pytest,_pytest,doctest,pdb,pdbpp\nset EXCLUDE_MODULES=%EXCLUDE_MODULES%,setuptools,pip,distutils,pkg_resources\nset EXCLUDE_MODULES=%EXCLUDE_MODULES%,email.mime,http.server,xmlrpc,pydoc\n\necho.\necho [1\u002F4] 清理旧编译...\nif exist dist rd \u002Fs \u002Fq dist\nif exist build rd \u002Fs \u002Fq build\n\necho.\necho [2\u002F4] Nuitka 编译中（应用 参考项目优化策略）...\necho - CPU 核心: %CPU_CORES% (使用 %BUILD_JOBS% 线程)\necho - 模块排除: %EXCLUDE_MODULES%\necho.\n\nnuitka --standalone ^\n    --windows-console-mode=disable ^\n    --lto=yes ^\n    --jobs=%BUILD_JOBS% ^\n    --enable-plugin=anti-bloat ^\n    --enable-plugin=tk-inter ^\n    --noinclude-pytest-mode=nofollow ^\n    --noinclude-setuptools-mode=nofollow ^\n    --nofollow-import-to=%EXCLUDE_MODULES% ^\n    --python-flag=no_docstrings ^\n    --output-dir=dist ^\n    --windows-icon-from-ico=%ICON_FILE% ^\n    --remove-output ^\n    %MAIN_FILE%\n\nif %errorlevel% neq 0 (\n    echo.\n    echo [错误] 编译失败！\n    pause\n    exit \u002Fb 1\n)\n\necho.\necho [3\u002F4] 统计编译结果...\nfor \u002Ff %%a in ('powershell -NoProfile -Command \"(Get-ChildItem -LiteralPath 'dist\\%APP_NAME%.dist' -Recurse -File | Measure-Object -Property Length -Sum).Sum\"') do set TOTAL_SIZE=%%a\nset TOTAL_SIZE=%TOTAL_SIZE:,=%\nset \u002Fa SIZE_MB=%TOTAL_SIZE% \u002F 1048576\necho - 编译后体积: %SIZE_MB% MB\n\necho.\necho [4\u002F4] 执行瘦身清理（参考 参考项目策略）...\npowershell -ExecutionPolicy Bypass -File slim_dist.ps1 -DistPath \"dist\\%APP_NAME%.dist\"\n\necho.\necho ========================================\necho 编译完成！\necho ========================================\npause\n```\n\n### 五、dist 瘦身脚本（参考项目级别清理）\n\n**保存为 `slim_dist.ps1`（和 build_optimized.bat 同目录）**：\n\n```powershell\nparam(\n    [string]$DistPath\n)\n\n$ErrorActionPreference = \"Continue\"  # 不静默吞错：删除失败会显示出来，避免假成功\n\nWrite-Host \"`n========================================\" -ForegroundColor Cyan\nWrite-Host \"dist 瘦身清理（参考 参考项目策略）\" -ForegroundColor Cyan\nWrite-Host \"========================================\" -ForegroundColor Cyan\n\nif (-not (Test-Path $DistPath)) {\n    Write-Host \"[错误] 找不到目录: $DistPath\" -ForegroundColor Red\n    exit 1\n}\n\n# 统计初始体积\n$InitialSize = (Get-ChildItem -Path $DistPath -Recurse -File | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nWrite-Host \"`n初始体积: $([math]::Round($InitialSize, 2)) MB\" -ForegroundColor Yellow\n\n# 参考项目特征：没有 .pdb, .pyi, __pycache__, test 等\nWrite-Host \"`n[应用 参考项目的清理策略...]\" -ForegroundColor Green\n\n# 1. 删除调试符号\nWrite-Host \"`n[1\u002F7] 删除 .pdb 调试符号...\" -ForegroundColor Green\n$pdbFiles = Get-ChildItem -Path $DistPath -Recurse -Include *.pdb -File\n$pdbSize = ($pdbFiles | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nif ($pdbFiles.Count -gt 0) {\n    $pdbFiles | Remove-Item -Force\n    Write-Host \"  删除 $($pdbFiles.Count) 个文件，节省 $([math]::Round($pdbSize, 2)) MB\"\n} else {\n    Write-Host \"  未发现 .pdb 文件（已优化）\" -ForegroundColor Gray\n}\n\n# 2. 删除类型提示\nWrite-Host \"`n[2\u002F7] 删除 .pyi 类型提示...\" -ForegroundColor Green\n$pyiFiles = Get-ChildItem -Path $DistPath -Recurse -Include *.pyi -File\n$pyiSize = ($pyiFiles | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nif ($pyiFiles.Count -gt 0) {\n    $pyiFiles | Remove-Item -Force\n    Write-Host \"  删除 $($pyiFiles.Count) 个文件，节省 $([math]::Round($pyiSize, 2)) MB\"\n} else {\n    Write-Host \"  未发现 .pyi 文件（已优化）\" -ForegroundColor Gray\n}\n\n# 3. 删除 __pycache__\nWrite-Host \"`n[3\u002F7] 删除 __pycache__ 缓存...\" -ForegroundColor Green\n$pycacheDirs = Get-ChildItem -Path $DistPath -Recurse -Directory -Filter \"__pycache__\"\n$pycacheSize = 0\nforeach ($dir in $pycacheDirs) {\n    $size = (Get-ChildItem -Path $dir.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum\n    $pycacheSize += $size\n    Remove-Item -Path $dir.FullName -Recurse -Force\n}\nif ($pycacheDirs.Count -gt 0) {\n    Write-Host \"  删除 $($pycacheDirs.Count) 个目录，节省 $([math]::Round($pycacheSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现 __pycache__（已优化）\" -ForegroundColor Gray\n}\n\n# 4. 删除测试目录\nWrite-Host \"`n[4\u002F7] 删除 test\u002Ftests 测试目录...\" -ForegroundColor Green\n$testDirs = Get-ChildItem -Path $DistPath -Recurse -Directory | Where-Object { $_.Name -match '^tests?$' }\n$testSize = 0\nforeach ($dir in $testDirs) {\n    $size = (Get-ChildItem -Path $dir.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum\n    $testSize += $size\n    Remove-Item -Path $dir.FullName -Recurse -Force\n}\nif ($testDirs.Count -gt 0) {\n    Write-Host \"  删除 $($testDirs.Count) 个目录，节省 $([math]::Round($testSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现测试目录（已优化）\" -ForegroundColor Gray\n}\n\n# 5. 删除文档和示例\nWrite-Host \"`n[5\u002F7] 删除 docs\u002Fexamples 文档目录...\" -ForegroundColor Green\n$docDirs = Get-ChildItem -Path $DistPath -Recurse -Directory | Where-Object { $_.Name -match '^(docs|examples|samples|demo)$' }\n$docSize = 0\nforeach ($dir in $docDirs) {\n    $size = (Get-ChildItem -Path $dir.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum\n    $docSize += $size\n    Remove-Item -Path $dir.FullName -Recurse -Force\n}\nif ($docDirs.Count -gt 0) {\n    Write-Host \"  删除 $($docDirs.Count) 个目录，节省 $([math]::Round($docSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现文档目录（已优化）\" -ForegroundColor Gray\n}\n\n# 6. 删除 .pyc 文件\nWrite-Host \"`n[6\u002F7] 删除 .pyc 字节码...\" -ForegroundColor Green\n$pycFiles = Get-ChildItem -Path $DistPath -Recurse -Include *.pyc -File\n$pycSize = ($pycFiles | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nif ($pycFiles.Count -gt 0) {\n    $pycFiles | Remove-Item -Force\n    Write-Host \"  删除 $($pycFiles.Count) 个文件，节省 $([math]::Round($pycSize, 2)) MB\"\n} else {\n    Write-Host \"  未发现 .pyc 文件（已优化）\" -ForegroundColor Gray\n}\n\n# 7. 精简 .dist-info 元数据\nWrite-Host \"`n[7\u002F7] 精简 .dist-info 元数据...\" -ForegroundColor Green\n$distInfoDirs = Get-ChildItem -Path $DistPath -Recurse -Directory -Filter \"*.dist-info\"\n$removedCount = 0\n$removedSize = 0\nforeach ($infoDir in $distInfoDirs) {\n    # 仅删安装期记账文件；保留 METADATA 与 entry_points.txt（运行期被 importlib.metadata 读取，删除会破坏插件发现）\n    $filesToRemove = @(\"RECORD\", \"INSTALLER\", \"direct_url.json\")\n    foreach ($fileName in $filesToRemove) {\n        $file = Join-Path $infoDir.FullName $fileName\n        if (Test-Path $file) {\n            $size = (Get-Item $file).Length\n            $removedSize += $size\n            Remove-Item $file -Force\n            $removedCount++\n        }\n    }\n}\nif ($removedCount -gt 0) {\n    Write-Host \"  删除 $removedCount 个元数据文件，节省 $([math]::Round($removedSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现可清理的元数据（已优化）\" -ForegroundColor Gray\n}\n\n# 统计最终体积\n$FinalSize = (Get-ChildItem -Path $DistPath -Recurse -File | Measure-Object -Property Length -Sum).Sum \u002F 1MB\n$SavedSize = $InitialSize - $FinalSize\n$SavedPercent = if ($InitialSize -gt 0) { ($SavedSize \u002F $InitialSize) * 100 } else { 0 }\n\nWrite-Host \"`n========================================\" -ForegroundColor Cyan\nWrite-Host \"清理完成！\" -ForegroundColor Green\nWrite-Host \"========================================\" -ForegroundColor Cyan\nWrite-Host \"初始体积: $([math]::Round($InitialSize, 2)) MB\" -ForegroundColor Yellow\nWrite-Host \"最终体积: $([math]::Round($FinalSize, 2)) MB\" -ForegroundColor Green\nWrite-Host \"节省空间: $([math]::Round($SavedSize, 2)) MB ($([math]::Round($SavedPercent, 1))%)\" -ForegroundColor Cyan\nWrite-Host \"========================================`n\" -ForegroundColor Cyan\n\n# 对比 参考项目\nWrite-Host \"[对比参考]\" -ForegroundColor Yellow\nWrite-Host \"参考项目总体积: 323 MB (包含 PyQt, OpenCV, Playwright 等重量级库)\" -ForegroundColor Gray\nWrite-Host \"如果你的项目是纯 Tkinter + 标准库，目标应该在 80-150 MB\" -ForegroundColor Gray\n```\n\n**预期效果**：节省 **15-30%** 体积\n\n### 六、DLL 依赖分析工具\n\n**保存为 `analyze_dlls.py`（用于找出体积大户）**：\n\n```python\n\"\"\"\nDLL 依赖分析工具\n参考 参考项目的 DLL 管理策略，帮助识别体积大户和优化建议\n\"\"\"\nimport sys\nfrom pathlib import Path\n\ndef analyze_dlls(dist_path: str):\n    \"\"\"分析 dist 目录中的 DLL 依赖\"\"\"\n    dist_dir = Path(dist_path)\n\n    if not dist_dir.exists():\n        print(f\"[错误] 目录不存在: {dist_path}\")\n        return\n\n    print(\"=\" * 70)\n    print(\"DLL 依赖分析（参考 参考项目策略）\")\n    print(\"=\" * 70)\n\n    # 收集所有 DLL\n    dll_files = list(dist_dir.rglob(\"*.dll\"))\n\n    if not dll_files:\n        print(\"\\n未发现 DLL 文件\")\n        return\n\n    # 按大小排序\n    dll_data = [(dll, dll.stat().st_size) for dll in dll_files]\n    dll_data.sort(key=lambda x: x[1], reverse=True)\n\n    total_size = sum(size for _, size in dll_data)\n\n    print(f\"\\n总 DLL 数量: {len(dll_files)}\")\n    print(f\"总 DLL 体积: {total_size \u002F 1024 \u002F 1024:.2f} MB\\n\")\n\n    # 参考项目对比\n    print(\"[对比参考] 参考项目的 DLL 情况:\")\n    print(\"  - 总数量: 71 个\")\n    print(\"  - 总体积: 93.23 MB\")\n    print(\"  - 最大的: libopenblas (26.85 MB), opengl32sw (15.25 MB)\\n\")\n\n    # 分析大于 3MB 的 DLL\n    large_dlls = [(dll, size) for dll, size in dll_data if size > 3 * 1024 * 1024]\n\n    if large_dlls:\n        print(\"=\" * 70)\n        print(\"WARNING:  大于 3MB 的 DLL（需重点关注）\")\n        print(\"=\" * 70)\n\n        for dll, size in large_dlls:\n            size_mb = size \u002F 1024 \u002F 1024\n            relative_path = dll.relative_to(dist_dir)\n            name_lower = dll.name.lower()\n\n            print(f\"\\n{size_mb:8.2f} MB  {dll.name}\")\n            print(f\"           位置: {relative_path.parent}\")\n\n            # 优化建议\n            suggestions = get_optimization_suggestion(name_lower)\n            if suggestions:\n                for suggestion in suggestions:\n                    print(f\"            {suggestion}\")\n\n    # 检查冗余 DLL\n    print(\"\\n\" + \"=\" * 70)\n    print(\" 冗余检查\")\n    print(\"=\" * 70)\n\n    # 检查调试版本\n    debug_dlls = [dll for dll, _ in dll_data if dll.stem.endswith('d')]\n    if debug_dlls:\n        print(f\"\\nWARNING:  发现 {len(debug_dlls)} 个调试版本 DLL（可以删除）:\")\n        for dll in debug_dlls:\n            print(f\"  - {dll.name}\")\n    else:\n        print(\"\\nPASS: 未发现调试版本 DLL（已优化）\")\n\n    # VC++ Runtime\n    vc_runtimes = [dll for dll, _ in dll_data if 'vcruntime' in dll.name.lower() or 'msvcp' in dll.name.lower()]\n    if vc_runtimes:\n        print(f\"\\n[VC++ Runtime 库] 发现 {len(vc_runtimes)} 个:\")\n        for dll in vc_runtimes:\n            size_mb = dll.stat().st_size \u002F 1024 \u002F 1024\n            print(f\"  - {dll.name} ({size_mb:.2f} MB)\")\n        print(\"   这些是必需的，参考项目也包含了这些文件\")\n\n    # 全部 DLL 列表\n    print(\"\\n\" + \"=\" * 70)\n    print(\" 完整 DLL 列表（按体积排序，前 20）\")\n    print(\"=\" * 70)\n    print(f\"\\n{'体积 (MB)':>10}  {'文件名':\u003C30}  位置\")\n    print(\"-\" * 70)\n\n    for dll, size in dll_data[:20]:\n        size_mb = size \u002F 1024 \u002F 1024\n        relative_path = dll.relative_to(dist_dir)\n        location = str(relative_path.parent) if relative_path.parent != Path('.') else \"根目录\"\n        print(f\"{size_mb:10.2f}  {dll.name:\u003C30}  {location}\")\n\n    if len(dll_data) > 20:\n        remaining_size = sum(size for _, size in dll_data[20:]) \u002F 1024 \u002F 1024\n        print(f\"... 还有 {len(dll_data) - 20} 个 DLL，共 {remaining_size:.2f} MB\")\n\n\ndef get_optimization_suggestion(dll_name: str) -> list:\n    \"\"\"根据 DLL 名称给出优化建议\"\"\"\n    suggestions = []\n\n    if \"openblas\" in dll_name or \"mkl\" in dll_name:\n        suggestions.append(\"数学运算库，参考项目的 libopenblas 有 26.85 MB\")\n        suggestions.append(\"如不需要高性能计算可考虑轻量版\")\n\n    elif \"opencv\" in dll_name or \"ffmpeg\" in dll_name:\n        suggestions.append(\"OpenCV 相关，参考项目的 opencv_videoio_ffmpeg 有 18.48 MB\")\n        suggestions.append(\"考虑用 opencv-python-headless\")\n\n    elif \"qt5\" in dll_name or \"qt6\" in dll_name or \"pyside\" in dll_name:\n        suggestions.append(\"Qt 库，参考项目的 Qt5Core 有 5.13 MB\")\n        suggestions.append(\"可排除不需要的模块（WebEngine, 3D, Charts）\")\n\n    elif \"opengl\" in dll_name and \"sw\" in dll_name:\n        suggestions.append(\"OpenGL 软件渲染器，参考项目保留了 15.25 MB\")\n        suggestions.append(\"通常可以删除（使用硬件渲染）\")\n\n    elif \"d3dcompiler\" in dll_name:\n        suggestions.append(\"DirectX 编译器，参考项目有 3.53 MB\")\n\n    elif \"mfc140\" in dll_name:\n        suggestions.append(\"MFC 库，参考项目有 4.89 MB\")\n\n    return suggestions\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 2:\n        print(\"用法: python analyze_dlls.py \u003Cdist目录路径>\")\n        print(\"示例: python analyze_dlls.py dist\u002Fmain.dist\")\n        sys.exit(1)\n\n    analyze_dlls(sys.argv[1])\n```\n\n**使用方法**：\n```bash\npython analyze_dlls.py dist\u002F你的软件名.dist\n```\n\n---\n\n## 完整优化工作流\n\n### 步骤 1：修改编译脚本配置\n\n编辑 `build_optimized.bat`，修改这 3 行：\n\n```batch\nset APP_NAME=你的软件名      REM 改成实际名称\nset MAIN_FILE=main.py        REM 你的主程序文件\nset ICON_FILE=icon.ico       REM 你的图标文件\n```\n\n### 步骤 2：一键编译+瘦身\n\n```bash\n# 在项目根目录执行\nbuild_optimized.bat\n```\n\n### 步骤 3：分析 DLL 依赖\n\n```bash\npython analyze_dlls.py dist\u002F你的软件名.dist\n```\n\n### 步骤 4：根据分析结果优化\n\n**如果用了 OpenCV** → 改用无头版\n```bash\npip uninstall opencv-python\npip install opencv-python-headless\n```\n\n**如果用了 Qt** → 排除不需要的模块\n```batch\n# 在编译命令中添加\n--nofollow-import-to=PyQt5.QtWebEngine,PyQt5.Qt3D,PyQt5.QtCharts\n```\n\n**删除软件渲染器**（如果不需要）\n```powershell\n# 在 dist 目录执行\nRemove-Item \"opengl32sw.dll\" -Force\n```\n\n---\n\n## VC++ 运行库处理方案\n\n### 方案一：静态链接（推荐）\n```bash\nnuitka --static-libpython=yes ...\n```\n\n### 方案二：捆绑运行库安装（商业发布推荐）\n在 Inno Setup 脚本中添加：\n\n```iss\n; WARNING: VC++ 运行库架构必须与 Python\u002FNuitka 构建架构一致。\n; 本 skill 推荐 32 位 Python，故默认捆绑 vc_redist.x86.exe；\n; 若用 64 位 Python 编译，请把下面两处改为 vc_redist.x64.exe。\n[Files]\nSource: \"{#MySourceDir}\\..\\vc_redist.x86.exe\"; DestDir: \"{tmp}\"; Flags: deleteafterinstall\n\n[Run]\nFilename: \"{tmp}\\vc_redist.x86.exe\"; Parameters: \"\u002Fquiet \u002Fnorestart\"; StatusMsg: \"正在安装运行库...\"; Flags: waituntilterminated\n```\n\n> 下载地址：[Microsoft Visual C++ Redistributable](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fcpp\u002Fwindows\u002Flatest-supported-vc-redist)\n\n---\n\n## Inno Setup 脚本模板（商业终极版）\n\n```iss\n; =====================================================================\n;  WARNING: 商业级 Python 安装脚本 (Inno Setup 6.x)\n;  特性：LZMA2 极限压缩 | 全中文 | 完整元数据 | 无残留卸载\n;  参考：参考项目(323 MB, LZMA2 压缩)\n; =====================================================================\n\n; --- 1. 参数定义 ---\n#define MyAppName        \"{{APP_NAME}}\"\n#define MyAppVersion     \"{{APP_VERSION}}\"\n#define MyAppPublisher   \"{{PUBLISHER}}\"\n#define MyAppURL         \"{{APP_URL}}\"\n#define MyAppExeName     \"{{EXE_NAME}}\"\n#define MySourceDir      \"{{SOURCE_DIR}}\"\n#define MyOutputDir      \"{{OUTPUT_DIR}}\"\n;#define MyIconPath      \"{{ICON_PATH}}\"\n\n[Setup]\n; --- 身份识别 ---\nAppId={{GENERATE_RANDOM_GUID}}\nAppName={#MyAppName}\nAppVersion={#MyAppVersion}\nAppPublisher={#MyAppPublisher}\nAppPublisherURL={#MyAppURL}\nAppSupportURL={#MyAppURL}\nAppUpdatesURL={#MyAppURL}\n\n; --- 安装路径与权限 ---\nDefaultDirName={autopf}\\{#MyAppName}\nDefaultGroupName={#MyAppName}\nDisableDirPage=no\nDisableProgramGroupPage=no\nPrivilegesRequired=admin\n\n; --- 输出设置 ---\nOutputDir={#MyOutputDir}\nOutputBaseFilename=Setup_{#MyAppName}_v{#MyAppVersion}\n\n; --- 视觉体验 ---\nWizardStyle=modern\n#ifdef MyIconPath\nSetupIconFile={#MyIconPath}\nUninstallDisplayIcon={app}\\{#MyAppExeName}\n#endif\n\n; ---  核心压缩 (参考 参考项目) ---\nCompression=lzma2\u002Fultra64\nSolidCompression=yes\nLZMAUseSeparateProcess=yes\n\n; --- 架构 ---\n; 注意：仅 64 位 Python 构建才设此项。本 skill 推荐 32 位 Python——\n; 32 位构建请保持注释，使应用按 32 位安装并与上面捆绑的 vc_redist.x86.exe 匹配。\n; 仅当用 64 位 Python 编译时才取消注释。\n;ArchitecturesInstallIn64BitMode=x64compatible\n\n[Languages]\nName: \"chinesesimplified\"; MessagesFile: \"compiler:Languages\\ChineseSimplified.isl\"\n\n[Files]\nSource: \"{#MySourceDir}\\*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs createallsubdirs\n\n[UninstallDelete]\nType: filesandordirs; Name: \"{app}\\*\"\n\n[Icons]\nName: \"{autodesktop}\\{#MyAppName}\"; Filename: \"{app}\\{#MyAppExeName}\"; Tasks: desktopicon\nName: \"{group}\\{#MyAppName}\"; Filename: \"{app}\\{#MyAppExeName}\"\nName: \"{group}\\卸载 {#MyAppName}\"; Filename: \"{uninstallexe}\"\n\n[Tasks]\nName: \"desktopicon\"; Description: \"{cm:CreateDesktopIcon}\"; GroupDescription: \"{cm:AdditionalIcons}\"; Flags: unchecked\n\n[Run]\nFilename: \"{app}\\{#MyAppExeName}\"; Description: \"{cm:LaunchProgram,{#MyAppName}}\"; Flags: nowait postinstall skipifsilent\n```\n\n---\n\n## 占位符说明\n\n| 占位符 | 说明 | 示例值 |\n|--------|------|--------|\n| `{{APP_NAME}}` | 软件显示名称 | `红墨批注` |\n| `{{APP_VERSION}}` | 版本号 | `1.0.0` |\n| `{{PUBLISHER}}` | 发布者\u002F公司名 | `MyCompany` |\n| `{{APP_URL}}` | 官网地址 | `https:\u002F\u002Fexample.com` |\n| `{{EXE_NAME}}` | 主程序文件名 | `RedInk.exe` |\n| `{{SOURCE_DIR}}` | Nuitka dist 文件夹路径 | `D:\\project\\dist\\RedInk.dist` |\n| `{{OUTPUT_DIR}}` | 安装包输出路径 | `D:\\project\\output` |\n| `{{ICON_PATH}}` | 图标文件路径 | `D:\\project\\icon.ico` |\n| `{{GENERATE_RANDOM_GUID}}` | **需生成唯一GUID** | 使用 Inno Setup \"Tools > Generate GUID\" |\n\n---\n\n## 常见问题 (FAQ)\n\n### Q1: 安装后双击程序无反应？\n1. 打开 CMD，手动运行 exe 查看错误信息\n2. 检查是否缺少 VC++ 运行库\n3. 检查 Nuitka 编译是否成功\n\n### Q2: 安装包体积过大？\n**优化方法**：\n1. 使用 32 位 Python 编译（节省 20-30%）\n2. 应用 参考项目的模块排除清单\n3. 启用 Anti-Bloat 插件\n4. 执行 dist 文件夹瘦身脚本\n5. 分析 DLL，移除不必要的大文件\n\n### Q3: 杀毒软件误报？\n**解决方案**：\n- 提交到主流杀毒厂商进行白名单申请\n- 购买代码签名证书（推荐：Sectigo, DigiCert）\n- 避免使用 UPX 压缩\n\n### Q4: 安装时提示 Windows 已保护你的电脑？\n- 购买 EV 代码签名证书（可立即获得信任）\n- 普通代码签名证书需要积累安装量后逐渐获得信任\n\n---\n\n## 实战问题处理记录（更新 2026-02-07）\n\n- **安装后提示缺少 python3xx.dll**：必须使用 Nuitka `--standalone`；确认 dist 内存在该 dll；不要打单文件版。\n- **安装后点击无反应**：GUI 启动期可能被重依赖阻塞；将重依赖延迟到\"开始导出\"再 import；添加日志排查。\n- **Nuitka + MinGW 在非 ASCII 路径报错**：把源码复制到 ASCII 目录再编译；设置 `PYTHONIOENCODING=utf-8`。\n- **Inno Setup 警告 `x64` 已弃用（仅 64 位构建需要 64 位安装模式时）**：改为 `ArchitecturesInstallIn64BitMode=x64compatible`；32 位构建无需此项。\n- **`--disable-console` 已废弃**：改用 `--windows-console-mode=disable`。\n- **dist 出现 `_nuitka_temp.exe`**：在 [Files] 中排除它。\n\n---\n\n## 优化效果预期\n\n| 优化组合 | 体积减少 | 启动提升 | 风险等级 |\n|----------|----------|----------|----------|\n| 基础编译 | 基准 | 基准 | 无 |\n| + `--lto=yes` | 5-10% | 10-20% | PASS: 无 |\n| + anti-bloat | 15-25% | - | PASS: 无 |\n| + 模块排除 | 20-35% | 5% | PASS: 无 |\n| + dist 瘦身 | 25-40% | - | PASS: 无 |\n| + 32 位编译 | 40-60% | - | PASS: 无 |\n| **全部组合** | **45-65%** | **15-25%** | PASS: **无风险** |\n\n> WARNING: **不建议使用 UPX 压缩**，虽然能进一步减小体积，但极易触发杀毒软件误报。\n\n---\n\n**基于 参考项目实战经验优化，助你打造商业级安装包！**\n","# Generating Python Installer (Commercial-Grade)\n\nYou are a **Python commercial deployment expert**. Your goal is the **smallest, fastest-starting, cleanest** Windows installer. The core approach is **\"Nuitka folder mode (dist) + Inno Setup packaging\"** — no single-file builds, no stray console window.\n\n## When to Activate\n\nActivate when the user explicitly asks for **advanced** Python packaging or size\u002Fstartup optimization on Windows:\n\n- Nuitka extreme \u002F commercial-grade compilation, smallest-size or fastest-startup builds\n- `dist` folder slimming, DLL footprint analysis, 32-bit vs 64-bit size tradeoffs\n- Inno Setup packaging with full metadata and a clean, residue-free uninstall\n\nThis skill targets advanced size\u002Fstartup optimization — not basic one-file \"script to exe\" conversion.\n\n## How It Works\n\n1. **Confirm build parameters** — app name, version, publisher, exe name, source\u002Foutput dirs, icon. Never auto-fill; ask the user.\n2. **Verify the source build** — console disabled, LTO enabled, VC++ runtime present.\n3. **Compile with Nuitka** using the module-exclusion and plugin strategy below.\n4. **Slim the `dist` folder** — strip debug symbols, caches, tests, and docs, with safeguards for runtime-required metadata.\n5. **Analyze DLLs** to find and trim the largest dependencies.\n6. **Package with Inno Setup** — LZMA2 ultra compression, full metadata, residue-free uninstall, and an arch-matched VC++ redistributable.\n\n## Examples\n\n- \"用 Nuitka 把这个 PySide2 项目打成最小体积的商业安装包\" → run the full workflow: recommend 32-bit, exclude WebEngine\u002F3D\u002FCharts, slim `dist`, package with Inno Setup.\n- \"我的 exe 有 400 MB，怎么瘦身到一半\" → analyze DLLs, switch to `opencv-python-headless`, drop `opengl32sw`, apply `dist` slimming.\n- \"安装后在纯净系统打不开\" → ensure the matching-arch VC++ redistributable is bundled in the Inno Setup script.\n\n---\n\n## 核心理念\n\n坚持 **\"Nuitka 文件夹模式(dist) + Inno Setup 封装\"** 方案。拒绝单文件版，拒绝黑窗。\n\n---\n\n## 实战参考案例（生产级 PySide2 桌面应用，323 MB，含 OpenCV \u002F Playwright）\n\n### 项目概况\n- **总体积**: 323 MB\n- **打包工具**: PyInstaller 4.7 (32位)\n- **主要依赖**: PySide2 (22.52 MB), OpenCV (62.38 MB), Playwright (76.74 MB)\n- **Python 版本**: Python 3.8 (32位)\n- **DLL 数量**: 71 个，总计 93.23 MB\n\n### 关键优化策略\n1. PASS: **使用 32 位 Python** → 体积减少 20-30%\n2. PASS: **base_library.zip 压缩标准库** → 0.74 MB\n3. PASS: **精简模块排除** → 无 pytest\u002Funittest\u002Fsetuptools\n4. PASS: **精简 Qt 插件** → 只保留必要插件\n\n### 体积分布\n\n| 组件 | 体积 | 占比 | 优化建议 |\n|------|------|------|---------|\n| playwright | 76.74 MB | 23.8% | 非必要可移除 |\n| OpenCV | 62.38 MB | 19.3% | 用 opencv-python-headless |\n| PySide2 | 22.52 MB | 7.0% | 排除 WebEngine\u002F3D\u002FCharts |\n| 其他依赖 | 161.36 MB | 49.9% | - |\n\n### 预期效果对比\n\n| 项目类型 | Nuitka 原始 | 优化后 | 参考项目实测 |\n|---------|------------|--------|----------------|\n| Tkinter + 标准库 | 150-250 MB | **80-120 MB** | - |\n| PyQt\u002FPySide | 200-400 MB | **120-250 MB** | 323 MB (含 OpenCV 等) |\n| 含 numpy\u002Fpandas | 300-600 MB | **180-350 MB** | - |\n\n---\n\n## 核心工作流 (Workflow) - WARNING: 严格执行\n\n当用户请求打包时，按照以下步骤操作：\n\n**步骤 1：强制参数确认（FAIL: 禁止使用默认值）**\n\n> **WARNING: 重要规则：以下所有参数必须逐一向用户确认，禁止自动填充或使用默认值！**\n\n必须向用户询问并确认以下信息（*等待用户明确回复后才能继续*）：\n\n| 参数 | 说明 | 示例 |\n|------|------|------|\n| **软件名称** (App Name) | 软件显示名称 | `红墨批注` |\n| **版本号** (Version) | 语义化版本号 | `1.0.0` |\n| **发布者\u002F公司名** (Publisher) | 控制面板显示的发布者 | `YourCompany` |\n| **主程序** (Exe Name) | 主可执行文件名 | `RedInk.exe` |\n| **源路径** (Source Dir) | Nuitka dist 文件夹绝对路径 | `D:\\project\\dist` |\n| **输出路径** (Output Dir) | 安装包生成位置 | `D:\\project\\output` |\n| **图标路径** (Icon Path) | .ico 文件绝对路径（可选但推荐） | `D:\\project\\icon.ico` |\n| **官网地址** (URL) | 可选，用于控制面板链接 | `https:\u002F\u002Fexample.com` |\n\n**询问模板：**\n> \"请提供以下打包参数，我需要您逐一确认：\n> 1. 软件名称：\n> 2. 版本号：\n> 3. 发布者\u002F公司名：\n> 4. 主程序文件名（如 xxx.exe）：\n> 5. 源路径（Nuitka dist 文件夹）：\n> 6. 输出路径（安装包保存位置）：\n> 7. 图标路径（.ico 文件，可留空）：\n> 8. 官网地址（可留空）：\n>\n> 请逐一填写，或回复\"跳过\"表示使用空值。\"\n\n**步骤 2：源文件质量与编译检查（关键）**\n在生成代码之前，必须向用户发出以下**关键确认**（因为 Inno Setup 只是打包工具，无法改变程序本身的运行属性）：\n\n> \"WARNING: **编译参数检查**：\n> 1. **去黑窗**：请确认您的 dist 文件夹是使用 `nuitka --windows-console-mode=disable` 编译的。（否则安装后依然会有黑框）\n> 2. **高性能**：请确认是否使用了 `--lto=yes`。（否则启动速度可能不理想）\n> 3. **运行库**：请确保 dist 文件夹内已包含必要的 VC++ 运行库，防止在纯净系统上无法运行。\n>\n> **确认源文件已准备好请回复\"确认\"，否则请先重新编译。**\"\n\n**步骤 3：生成代码**\n用户确认后，输出包含 **完整元数据** 和 **卸载图标修复** 的代码。\n\n---\n\n## Nuitka 极限优化编译（基于 参考项目经验）\n\n### 一、32 位 vs 64 位选择策略\n\n**参考项目使用 32 位 Python 的原因**：\n\n| 组件 | 64位体积 | 32位体积 | 节省 |\n|------|---------|---------|------|\n| python3x.dll | ~4.5 MB | ~3.8 MB | 15% |\n| Qt5Core.dll | ~8 MB | ~5 MB | 37% |\n| numpy | ~30 MB | ~20 MB | 33% |\n| **总体** | 基准 | **-20~30%** | - |\n\n**推荐使用 32 位条件**：\n- PASS: 程序内存占用 \u003C 2GB\n- PASS: 不处理超大文件（\u003C 2GB）\n- PASS: 目标用户是普通办公电脑\n\n**32 位编译方法**：\n```bash\n# 1. 安装 32 位 Python（和 64 位可以共存）\n# 下载地址：https:\u002F\u002Fwww.python.org\u002Fdownloads\u002Fwindows\u002F\n\n# 2. 用 32 位 Python 安装依赖\npy -3.12-32 -m pip install -r requirements.txt\n\n# 3. 用 32 位 Python 编译\npy -3.12-32 -m nuitka --standalone ...你的参数\n```\n\n### 二、模块排除清单（参考项目验证过的）\n\n**安全排除列表**（运行时不需要）：\n```\nunittest,test,pytest,_pytest,doctest,pdb,pdbpp,\nsetuptools,pip,distutils,pkg_resources,\nemail.mime,http.server,xmlrpc,pydoc\n```\n\n**预期效果**：节省 **30-50 MB**\n\n### 三、GUI 框架专用优化\n\n#### Tkinter 极限优化（推荐，最轻量）\n```bash\nnuitka --standalone --windows-console-mode=disable ^\n    --lto=yes ^\n    --jobs=8 ^\n    --enable-plugin=tk-inter ^\n    --enable-plugin=anti-bloat ^\n    --noinclude-pytest-mode=nofollow ^\n    --noinclude-setuptools-mode=nofollow ^\n    --nofollow-import-to=unittest,test,pytest,_pytest,doctest,pdb,pdbpp ^\n    --nofollow-import-to=setuptools,pip,distutils,pkg_resources ^\n    --nofollow-import-to=email.mime,http.server,xmlrpc,pydoc ^\n    --python-flag=no_docstrings ^\n    --output-dir=dist ^\n    --windows-icon-from-ico=icon.ico ^\n    --remove-output ^\n    main.py\n```\n\n**预期体积**：80-120 MB（优化后）\n\n#### PyQt5 \u002F PySide2 优化\n```bash\nnuitka --standalone --windows-console-mode=disable ^\n    --lto=yes ^\n    --jobs=8 ^\n    --enable-plugin=pyqt5 ^\n    --enable-plugin=anti-bloat ^\n    --noinclude-pytest-mode=nofollow ^\n    --noinclude-setuptools-mode=nofollow ^\n    --nofollow-import-to=unittest,test,pytest,_pytest,doctest,pdb ^\n    --nofollow-import-to=setuptools,pip,distutils,pkg_resources ^\n    --nofollow-import-to=PyQt5.QtWebEngine,PyQt5.QtWebEngineWidgets ^\n    --nofollow-import-to=PyQt5.Qt3D,PyQt5.QtCharts ^\n    --python-flag=no_docstrings ^\n    --include-qt-plugins=sensible,styles,platforms ^\n    --output-dir=dist ^\n    --windows-icon-from-ico=icon.ico ^\n    --remove-output ^\n    main.py\n```\n\n**预期体积**：120-250 MB（优化后）\n\n### 四、一键编译脚本模板\n\n**保存为 `build_optimized.bat`（项目根目录）**：\n\n```batch\n@echo off\nchcp 65001 >nul\nsetlocal enabledelayedexpansion\n\necho ========================================\necho Nuitka 极限优化编译（参考 参考项目）\necho ========================================\n\nREM === 配置区域（请修改为你的实际值） ===\nset APP_NAME=你的软件名\nset MAIN_FILE=main.py\nset ICON_FILE=icon.ico\n\nREM === 自动检测 CPU 核心数 ===\nREM 用 Windows 自带环境变量（wmic 在 Win11 22H2+ 已移除，探不到会让 --jobs=0 单线程编译）\nset CPU_CORES=%NUMBER_OF_PROCESSORS%\nif not defined CPU_CORES set CPU_CORES=4\nset \u002Fa BUILD_JOBS=%CPU_CORES%\n\nREM === 参考项目的模块排除清单 ===\nset EXCLUDE_MODULES=unittest,test,pytest,_pytest,doctest,pdb,pdbpp\nset EXCLUDE_MODULES=%EXCLUDE_MODULES%,setuptools,pip,distutils,pkg_resources\nset EXCLUDE_MODULES=%EXCLUDE_MODULES%,email.mime,http.server,xmlrpc,pydoc\n\necho.\necho [1\u002F4] 清理旧编译...\nif exist dist rd \u002Fs \u002Fq dist\nif exist build rd \u002Fs \u002Fq build\n\necho.\necho [2\u002F4] Nuitka 编译中（应用 参考项目优化策略）...\necho - CPU 核心: %CPU_CORES% (使用 %BUILD_JOBS% 线程)\necho - 模块排除: %EXCLUDE_MODULES%\necho.\n\nnuitka --standalone ^\n    --windows-console-mode=disable ^\n    --lto=yes ^\n    --jobs=%BUILD_JOBS% ^\n    --enable-plugin=anti-bloat ^\n    --enable-plugin=tk-inter ^\n    --noinclude-pytest-mode=nofollow ^\n    --noinclude-setuptools-mode=nofollow ^\n    --nofollow-import-to=%EXCLUDE_MODULES% ^\n    --python-flag=no_docstrings ^\n    --output-dir=dist ^\n    --windows-icon-from-ico=%ICON_FILE% ^\n    --remove-output ^\n    %MAIN_FILE%\n\nif %errorlevel% neq 0 (\n    echo.\n    echo [错误] 编译失败！\n    pause\n    exit \u002Fb 1\n)\n\necho.\necho [3\u002F4] 统计编译结果...\nfor \u002Ff %%a in ('powershell -NoProfile -Command \"(Get-ChildItem -LiteralPath 'dist\\%APP_NAME%.dist' -Recurse -File | Measure-Object -Property Length -Sum).Sum\"') do set TOTAL_SIZE=%%a\nset TOTAL_SIZE=%TOTAL_SIZE:,=%\nset \u002Fa SIZE_MB=%TOTAL_SIZE% \u002F 1048576\necho - 编译后体积: %SIZE_MB% MB\n\necho.\necho [4\u002F4] 执行瘦身清理（参考 参考项目策略）...\npowershell -ExecutionPolicy Bypass -File slim_dist.ps1 -DistPath \"dist\\%APP_NAME%.dist\"\n\necho.\necho ========================================\necho 编译完成！\necho ========================================\npause\n```\n\n### 五、dist 瘦身脚本（参考项目级别清理）\n\n**保存为 `slim_dist.ps1`（和 build_optimized.bat 同目录）**：\n\n```powershell\nparam(\n    [string]$DistPath\n)\n\n$ErrorActionPreference = \"Continue\"  # 不静默吞错：删除失败会显示出来，避免假成功\n\nWrite-Host \"`n========================================\" -ForegroundColor Cyan\nWrite-Host \"dist 瘦身清理（参考 参考项目策略）\" -ForegroundColor Cyan\nWrite-Host \"========================================\" -ForegroundColor Cyan\n\nif (-not (Test-Path $DistPath)) {\n    Write-Host \"[错误] 找不到目录: $DistPath\" -ForegroundColor Red\n    exit 1\n}\n\n# 统计初始体积\n$InitialSize = (Get-ChildItem -Path $DistPath -Recurse -File | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nWrite-Host \"`n初始体积: $([math]::Round($InitialSize, 2)) MB\" -ForegroundColor Yellow\n\n# 参考项目特征：没有 .pdb, .pyi, __pycache__, test 等\nWrite-Host \"`n[应用 参考项目的清理策略...]\" -ForegroundColor Green\n\n# 1. 删除调试符号\nWrite-Host \"`n[1\u002F7] 删除 .pdb 调试符号...\" -ForegroundColor Green\n$pdbFiles = Get-ChildItem -Path $DistPath -Recurse -Include *.pdb -File\n$pdbSize = ($pdbFiles | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nif ($pdbFiles.Count -gt 0) {\n    $pdbFiles | Remove-Item -Force\n    Write-Host \"  删除 $($pdbFiles.Count) 个文件，节省 $([math]::Round($pdbSize, 2)) MB\"\n} else {\n    Write-Host \"  未发现 .pdb 文件（已优化）\" -ForegroundColor Gray\n}\n\n# 2. 删除类型提示\nWrite-Host \"`n[2\u002F7] 删除 .pyi 类型提示...\" -ForegroundColor Green\n$pyiFiles = Get-ChildItem -Path $DistPath -Recurse -Include *.pyi -File\n$pyiSize = ($pyiFiles | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nif ($pyiFiles.Count -gt 0) {\n    $pyiFiles | Remove-Item -Force\n    Write-Host \"  删除 $($pyiFiles.Count) 个文件，节省 $([math]::Round($pyiSize, 2)) MB\"\n} else {\n    Write-Host \"  未发现 .pyi 文件（已优化）\" -ForegroundColor Gray\n}\n\n# 3. 删除 __pycache__\nWrite-Host \"`n[3\u002F7] 删除 __pycache__ 缓存...\" -ForegroundColor Green\n$pycacheDirs = Get-ChildItem -Path $DistPath -Recurse -Directory -Filter \"__pycache__\"\n$pycacheSize = 0\nforeach ($dir in $pycacheDirs) {\n    $size = (Get-ChildItem -Path $dir.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum\n    $pycacheSize += $size\n    Remove-Item -Path $dir.FullName -Recurse -Force\n}\nif ($pycacheDirs.Count -gt 0) {\n    Write-Host \"  删除 $($pycacheDirs.Count) 个目录，节省 $([math]::Round($pycacheSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现 __pycache__（已优化）\" -ForegroundColor Gray\n}\n\n# 4. 删除测试目录\nWrite-Host \"`n[4\u002F7] 删除 test\u002Ftests 测试目录...\" -ForegroundColor Green\n$testDirs = Get-ChildItem -Path $DistPath -Recurse -Directory | Where-Object { $_.Name -match '^tests?$' }\n$testSize = 0\nforeach ($dir in $testDirs) {\n    $size = (Get-ChildItem -Path $dir.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum\n    $testSize += $size\n    Remove-Item -Path $dir.FullName -Recurse -Force\n}\nif ($testDirs.Count -gt 0) {\n    Write-Host \"  删除 $($testDirs.Count) 个目录，节省 $([math]::Round($testSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现测试目录（已优化）\" -ForegroundColor Gray\n}\n\n# 5. 删除文档和示例\nWrite-Host \"`n[5\u002F7] 删除 docs\u002Fexamples 文档目录...\" -ForegroundColor Green\n$docDirs = Get-ChildItem -Path $DistPath -Recurse -Directory | Where-Object { $_.Name -match '^(docs|examples|samples|demo)$' }\n$docSize = 0\nforeach ($dir in $docDirs) {\n    $size = (Get-ChildItem -Path $dir.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum\n    $docSize += $size\n    Remove-Item -Path $dir.FullName -Recurse -Force\n}\nif ($docDirs.Count -gt 0) {\n    Write-Host \"  删除 $($docDirs.Count) 个目录，节省 $([math]::Round($docSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现文档目录（已优化）\" -ForegroundColor Gray\n}\n\n# 6. 删除 .pyc 文件\nWrite-Host \"`n[6\u002F7] 删除 .pyc 字节码...\" -ForegroundColor Green\n$pycFiles = Get-ChildItem -Path $DistPath -Recurse -Include *.pyc -File\n$pycSize = ($pycFiles | Measure-Object -Property Length -Sum).Sum \u002F 1MB\nif ($pycFiles.Count -gt 0) {\n    $pycFiles | Remove-Item -Force\n    Write-Host \"  删除 $($pycFiles.Count) 个文件，节省 $([math]::Round($pycSize, 2)) MB\"\n} else {\n    Write-Host \"  未发现 .pyc 文件（已优化）\" -ForegroundColor Gray\n}\n\n# 7. 精简 .dist-info 元数据\nWrite-Host \"`n[7\u002F7] 精简 .dist-info 元数据...\" -ForegroundColor Green\n$distInfoDirs = Get-ChildItem -Path $DistPath -Recurse -Directory -Filter \"*.dist-info\"\n$removedCount = 0\n$removedSize = 0\nforeach ($infoDir in $distInfoDirs) {\n    # 仅删安装期记账文件；保留 METADATA 与 entry_points.txt（运行期被 importlib.metadata 读取，删除会破坏插件发现）\n    $filesToRemove = @(\"RECORD\", \"INSTALLER\", \"direct_url.json\")\n    foreach ($fileName in $filesToRemove) {\n        $file = Join-Path $infoDir.FullName $fileName\n        if (Test-Path $file) {\n            $size = (Get-Item $file).Length\n            $removedSize += $size\n            Remove-Item $file -Force\n            $removedCount++\n        }\n    }\n}\nif ($removedCount -gt 0) {\n    Write-Host \"  删除 $removedCount 个元数据文件，节省 $([math]::Round($removedSize \u002F 1MB, 2)) MB\"\n} else {\n    Write-Host \"  未发现可清理的元数据（已优化）\" -ForegroundColor Gray\n}\n\n# 统计最终体积\n$FinalSize = (Get-ChildItem -Path $DistPath -Recurse -File | Measure-Object -Property Length -Sum).Sum \u002F 1MB\n$SavedSize = $InitialSize - $FinalSize\n$SavedPercent = if ($InitialSize -gt 0) { ($SavedSize \u002F $InitialSize) * 100 } else { 0 }\n\nWrite-Host \"`n========================================\" -ForegroundColor Cyan\nWrite-Host \"清理完成！\" -ForegroundColor Green\nWrite-Host \"========================================\" -ForegroundColor Cyan\nWrite-Host \"初始体积: $([math]::Round($InitialSize, 2)) MB\" -ForegroundColor Yellow\nWrite-Host \"最终体积: $([math]::Round($FinalSize, 2)) MB\" -ForegroundColor Green\nWrite-Host \"节省空间: $([math]::Round($SavedSize, 2)) MB ($([math]::Round($SavedPercent, 1))%)\" -ForegroundColor Cyan\nWrite-Host \"========================================`n\" -ForegroundColor Cyan\n\n# 对比 参考项目\nWrite-Host \"[对比参考]\" -ForegroundColor Yellow\nWrite-Host \"参考项目总体积: 323 MB (包含 PyQt, OpenCV, Playwright 等重量级库)\" -ForegroundColor Gray\nWrite-Host \"如果你的项目是纯 Tkinter + 标准库，目标应该在 80-150 MB\" -ForegroundColor Gray\n```\n\n**预期效果**：节省 **15-30%** 体积\n\n### 六、DLL 依赖分析工具\n\n**保存为 `analyze_dlls.py`（用于找出体积大户）**：\n\n```python\n\"\"\"\nDLL 依赖分析工具\n参考 参考项目的 DLL 管理策略，帮助识别体积大户和优化建议\n\"\"\"\nimport sys\nfrom pathlib import Path\n\ndef analyze_dlls(dist_path: str):\n    \"\"\"分析 dist 目录中的 DLL 依赖\"\"\"\n    dist_dir = Path(dist_path)\n\n    if not dist_dir.exists():\n        print(f\"[错误] 目录不存在: {dist_path}\")\n        return\n\n    print(\"=\" * 70)\n    print(\"DLL 依赖分析（参考 参考项目策略）\")\n    print(\"=\" * 70)\n\n    # 收集所有 DLL\n    dll_files = list(dist_dir.rglob(\"*.dll\"))\n\n    if not dll_files:\n        print(\"\\n未发现 DLL 文件\")\n        return\n\n    # 按大小排序\n    dll_data = [(dll, dll.stat().st_size) for dll in dll_files]\n    dll_data.sort(key=lambda x: x[1], reverse=True)\n\n    total_size = sum(size for _, size in dll_data)\n\n    print(f\"\\n总 DLL 数量: {len(dll_files)}\")\n    print(f\"总 DLL 体积: {total_size \u002F 1024 \u002F 1024:.2f} MB\\n\")\n\n    # 参考项目对比\n    print(\"[对比参考] 参考项目的 DLL 情况:\")\n    print(\"  - 总数量: 71 个\")\n    print(\"  - 总体积: 93.23 MB\")\n    print(\"  - 最大的: libopenblas (26.85 MB), opengl32sw (15.25 MB)\\n\")\n\n    # 分析大于 3MB 的 DLL\n    large_dlls = [(dll, size) for dll, size in dll_data if size > 3 * 1024 * 1024]\n\n    if large_dlls:\n        print(\"=\" * 70)\n        print(\"WARNING:  大于 3MB 的 DLL（需重点关注）\")\n        print(\"=\" * 70)\n\n        for dll, size in large_dlls:\n            size_mb = size \u002F 1024 \u002F 1024\n            relative_path = dll.relative_to(dist_dir)\n            name_lower = dll.name.lower()\n\n            print(f\"\\n{size_mb:8.2f} MB  {dll.name}\")\n            print(f\"           位置: {relative_path.parent}\")\n\n            # 优化建议\n            suggestions = get_optimization_suggestion(name_lower)\n            if suggestions:\n                for suggestion in suggestions:\n                    print(f\"            {suggestion}\")\n\n    # 检查冗余 DLL\n    print(\"\\n\" + \"=\" * 70)\n    print(\" 冗余检查\")\n    print(\"=\" * 70)\n\n    # 检查调试版本\n    debug_dlls = [dll for dll, _ in dll_data if dll.stem.endswith('d')]\n    if debug_dlls:\n        print(f\"\\nWARNING:  发现 {len(debug_dlls)} 个调试版本 DLL（可以删除）:\")\n        for dll in debug_dlls:\n            print(f\"  - {dll.name}\")\n    else:\n        print(\"\\nPASS: 未发现调试版本 DLL（已优化）\")\n\n    # VC++ Runtime\n    vc_runtimes = [dll for dll, _ in dll_data if 'vcruntime' in dll.name.lower() or 'msvcp' in dll.name.lower()]\n    if vc_runtimes:\n        print(f\"\\n[VC++ Runtime 库] 发现 {len(vc_runtimes)} 个:\")\n        for dll in vc_runtimes:\n            size_mb = dll.stat().st_size \u002F 1024 \u002F 1024\n            print(f\"  - {dll.name} ({size_mb:.2f} MB)\")\n        print(\"   这些是必需的，参考项目也包含了这些文件\")\n\n    # 全部 DLL 列表\n    print(\"\\n\" + \"=\" * 70)\n    print(\" 完整 DLL 列表（按体积排序，前 20）\")\n    print(\"=\" * 70)\n    print(f\"\\n{'体积 (MB)':>10}  {'文件名':\u003C30}  位置\")\n    print(\"-\" * 70)\n\n    for dll, size in dll_data[:20]:\n        size_mb = size \u002F 1024 \u002F 1024\n        relative_path = dll.relative_to(dist_dir)\n        location = str(relative_path.parent) if relative_path.parent != Path('.') else \"根目录\"\n        print(f\"{size_mb:10.2f}  {dll.name:\u003C30}  {location}\")\n\n    if len(dll_data) > 20:\n        remaining_size = sum(size for _, size in dll_data[20:]) \u002F 1024 \u002F 1024\n        print(f\"... 还有 {len(dll_data) - 20} 个 DLL，共 {remaining_size:.2f} MB\")\n\n\ndef get_optimization_suggestion(dll_name: str) -> list:\n    \"\"\"根据 DLL 名称给出优化建议\"\"\"\n    suggestions = []\n\n    if \"openblas\" in dll_name or \"mkl\" in dll_name:\n        suggestions.append(\"数学运算库，参考项目的 libopenblas 有 26.85 MB\")\n        suggestions.append(\"如不需要高性能计算可考虑轻量版\")\n\n    elif \"opencv\" in dll_name or \"ffmpeg\" in dll_name:\n        suggestions.append(\"OpenCV 相关，参考项目的 opencv_videoio_ffmpeg 有 18.48 MB\")\n        suggestions.append(\"考虑用 opencv-python-headless\")\n\n    elif \"qt5\" in dll_name or \"qt6\" in dll_name or \"pyside\" in dll_name:\n        suggestions.append(\"Qt 库，参考项目的 Qt5Core 有 5.13 MB\")\n        suggestions.append(\"可排除不需要的模块（WebEngine, 3D, Charts）\")\n\n    elif \"opengl\" in dll_name and \"sw\" in dll_name:\n        suggestions.append(\"OpenGL 软件渲染器，参考项目保留了 15.25 MB\")\n        suggestions.append(\"通常可以删除（使用硬件渲染）\")\n\n    elif \"d3dcompiler\" in dll_name:\n        suggestions.append(\"DirectX 编译器，参考项目有 3.53 MB\")\n\n    elif \"mfc140\" in dll_name:\n        suggestions.append(\"MFC 库，参考项目有 4.89 MB\")\n\n    return suggestions\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 2:\n        print(\"用法: python analyze_dlls.py \u003Cdist目录路径>\")\n        print(\"示例: python analyze_dlls.py dist\u002Fmain.dist\")\n        sys.exit(1)\n\n    analyze_dlls(sys.argv[1])\n```\n\n**使用方法**：\n```bash\npython analyze_dlls.py dist\u002F你的软件名.dist\n```\n\n---\n\n## 完整优化工作流\n\n### 步骤 1：修改编译脚本配置\n\n编辑 `build_optimized.bat`，修改这 3 行：\n\n```batch\nset APP_NAME=你的软件名      REM 改成实际名称\nset MAIN_FILE=main.py        REM 你的主程序文件\nset ICON_FILE=icon.ico       REM 你的图标文件\n```\n\n### 步骤 2：一键编译+瘦身\n\n```bash\n# 在项目根目录执行\nbuild_optimized.bat\n```\n\n### 步骤 3：分析 DLL 依赖\n\n```bash\npython analyze_dlls.py dist\u002F你的软件名.dist\n```\n\n### 步骤 4：根据分析结果优化\n\n**如果用了 OpenCV** → 改用无头版\n```bash\npip uninstall opencv-python\npip install opencv-python-headless\n```\n\n**如果用了 Qt** → 排除不需要的模块\n```batch\n# 在编译命令中添加\n--nofollow-import-to=PyQt5.QtWebEngine,PyQt5.Qt3D,PyQt5.QtCharts\n```\n\n**删除软件渲染器**（如果不需要）\n```powershell\n# 在 dist 目录执行\nRemove-Item \"opengl32sw.dll\" -Force\n```\n\n---\n\n## VC++ 运行库处理方案\n\n### 方案一：静态链接（推荐）\n```bash\nnuitka --static-libpython=yes ...\n```\n\n### 方案二：捆绑运行库安装（商业发布推荐）\n在 Inno Setup 脚本中添加：\n\n```iss\n; WARNING: VC++ 运行库架构必须与 Python\u002FNuitka 构建架构一致。\n; 本 skill 推荐 32 位 Python，故默认捆绑 vc_redist.x86.exe；\n; 若用 64 位 Python 编译，请把下面两处改为 vc_redist.x64.exe。\n[Files]\nSource: \"{#MySourceDir}\\..\\vc_redist.x86.exe\"; DestDir: \"{tmp}\"; Flags: deleteafterinstall\n\n[Run]\nFilename: \"{tmp}\\vc_redist.x86.exe\"; Parameters: \"\u002Fquiet \u002Fnorestart\"; StatusMsg: \"正在安装运行库...\"; Flags: waituntilterminated\n```\n\n> 下载地址：[Microsoft Visual C++ Redistributable](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fcpp\u002Fwindows\u002Flatest-supported-vc-redist)\n\n---\n\n## Inno Setup 脚本模板（商业终极版）\n\n```iss\n; =====================================================================\n;  WARNING: 商业级 Python 安装脚本 (Inno Setup 6.x)\n;  特性：LZMA2 极限压缩 | 全中文 | 完整元数据 | 无残留卸载\n;  参考：参考项目(323 MB, LZMA2 压缩)\n; =====================================================================\n\n; --- 1. 参数定义 ---\n#define MyAppName        \"{{APP_NAME}}\"\n#define MyAppVersion     \"{{APP_VERSION}}\"\n#define MyAppPublisher   \"{{PUBLISHER}}\"\n#define MyAppURL         \"{{APP_URL}}\"\n#define MyAppExeName     \"{{EXE_NAME}}\"\n#define MySourceDir      \"{{SOURCE_DIR}}\"\n#define MyOutputDir      \"{{OUTPUT_DIR}}\"\n;#define MyIconPath      \"{{ICON_PATH}}\"\n\n[Setup]\n; --- 身份识别 ---\nAppId={{GENERATE_RANDOM_GUID}}\nAppName={#MyAppName}\nAppVersion={#MyAppVersion}\nAppPublisher={#MyAppPublisher}\nAppPublisherURL={#MyAppURL}\nAppSupportURL={#MyAppURL}\nAppUpdatesURL={#MyAppURL}\n\n; --- 安装路径与权限 ---\nDefaultDirName={autopf}\\{#MyAppName}\nDefaultGroupName={#MyAppName}\nDisableDirPage=no\nDisableProgramGroupPage=no\nPrivilegesRequired=admin\n\n; --- 输出设置 ---\nOutputDir={#MyOutputDir}\nOutputBaseFilename=Setup_{#MyAppName}_v{#MyAppVersion}\n\n; --- 视觉体验 ---\nWizardStyle=modern\n#ifdef MyIconPath\nSetupIconFile={#MyIconPath}\nUninstallDisplayIcon={app}\\{#MyAppExeName}\n#endif\n\n; ---  核心压缩 (参考 参考项目) ---\nCompression=lzma2\u002Fultra64\nSolidCompression=yes\nLZMAUseSeparateProcess=yes\n\n; --- 架构 ---\n; 注意：仅 64 位 Python 构建才设此项。本 skill 推荐 32 位 Python——\n; 32 位构建请保持注释，使应用按 32 位安装并与上面捆绑的 vc_redist.x86.exe 匹配。\n; 仅当用 64 位 Python 编译时才取消注释。\n;ArchitecturesInstallIn64BitMode=x64compatible\n\n[Languages]\nName: \"chinesesimplified\"; MessagesFile: \"compiler:Languages\\ChineseSimplified.isl\"\n\n[Files]\nSource: \"{#MySourceDir}\\*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs createallsubdirs\n\n[UninstallDelete]\nType: filesandordirs; Name: \"{app}\\*\"\n\n[Icons]\nName: \"{autodesktop}\\{#MyAppName}\"; Filename: \"{app}\\{#MyAppExeName}\"; Tasks: desktopicon\nName: \"{group}\\{#MyAppName}\"; Filename: \"{app}\\{#MyAppExeName}\"\nName: \"{group}\\卸载 {#MyAppName}\"; Filename: \"{uninstallexe}\"\n\n[Tasks]\nName: \"desktopicon\"; Description: \"{cm:CreateDesktopIcon}\"; GroupDescription: \"{cm:AdditionalIcons}\"; Flags: unchecked\n\n[Run]\nFilename: \"{app}\\{#MyAppExeName}\"; Description: \"{cm:LaunchProgram,{#MyAppName}}\"; Flags: nowait postinstall skipifsilent\n```\n\n---\n\n## 占位符说明\n\n| 占位符 | 说明 | 示例值 |\n|--------|------|--------|\n| `{{APP_NAME}}` | 软件显示名称 | `红墨批注` |\n| `{{APP_VERSION}}` | 版本号 | `1.0.0` |\n| `{{PUBLISHER}}` | 发布者\u002F公司名 | `MyCompany` |\n| `{{APP_URL}}` | 官网地址 | `https:\u002F\u002Fexample.com` |\n| `{{EXE_NAME}}` | 主程序文件名 | `RedInk.exe` |\n| `{{SOURCE_DIR}}` | Nuitka dist 文件夹路径 | `D:\\project\\dist\\RedInk.dist` |\n| `{{OUTPUT_DIR}}` | 安装包输出路径 | `D:\\project\\output` |\n| `{{ICON_PATH}}` | 图标文件路径 | `D:\\project\\icon.ico` |\n| `{{GENERATE_RANDOM_GUID}}` | **需生成唯一GUID** | 使用 Inno Setup \"Tools > Generate GUID\" |\n\n---\n\n## 常见问题 (FAQ)\n\n### Q1: 安装后双击程序无反应？\n1. 打开 CMD，手动运行 exe 查看错误信息\n2. 检查是否缺少 VC++ 运行库\n3. 检查 Nuitka 编译是否成功\n\n### Q2: 安装包体积过大？\n**优化方法**：\n1. 使用 32 位 Python 编译（节省 20-30%）\n2. 应用 参考项目的模块排除清单\n3. 启用 Anti-Bloat 插件\n4. 执行 dist 文件夹瘦身脚本\n5. 分析 DLL，移除不必要的大文件\n\n### Q3: 杀毒软件误报？\n**解决方案**：\n- 提交到主流杀毒厂商进行白名单申请\n- 购买代码签名证书（推荐：Sectigo, DigiCert）\n- 避免使用 UPX 压缩\n\n### Q4: 安装时提示 Windows 已保护你的电脑？\n- 购买 EV 代码签名证书（可立即获得信任）\n- 普通代码签名证书需要积累安装量后逐渐获得信任\n\n---\n\n## 实战问题处理记录（更新 2026-02-07）\n\n- **安装后提示缺少 python3xx.dll**：必须使用 Nuitka `--standalone`；确认 dist 内存在该 dll；不要打单文件版。\n- **安装后点击无反应**：GUI 启动期可能被重依赖阻塞；将重依赖延迟到\"开始导出\"再 import；添加日志排查。\n- **Nuitka + MinGW 在非 ASCII 路径报错**：把源码复制到 ASCII 目录再编译；设置 `PYTHONIOENCODING=utf-8`。\n- **Inno Setup 警告 `x64` 已弃用（仅 64 位构建需要 64 位安装模式时）**：改为 `ArchitecturesInstallIn64BitMode=x64compatible`；32 位构建无需此项。\n- **`--disable-console` 已废弃**：改用 `--windows-console-mode=disable`。\n- **dist 出现 `_nuitka_temp.exe`**：在 [Files] 中排除它。\n\n---\n\n## 优化效果预期\n\n| 优化组合 | 体积减少 | 启动提升 | 风险等级 |\n|----------|----------|----------|----------|\n| 基础编译 | 基准 | 基准 | 无 |\n| + `--lto=yes` | 5-10% | 10-20% | PASS: 无 |\n| + anti-bloat | 15-25% | - | PASS: 无 |\n| + 模块排除 | 20-35% | 5% | PASS: 无 |\n| + dist 瘦身 | 25-40% | - | PASS: 无 |\n| + 32 位编译 | 40-60% | - | PASS: 无 |\n| **全部组合** | **45-65%** | **15-25%** | PASS: **无风险** |\n\n> WARNING: **不建议使用 UPX 压缩**，虽然能进一步减小体积，但极易触发杀毒软件误报。\n\n---\n\n**基于 参考项目实战经验优化，助你打造商业级安装包！**\n",{"name":5,"description":7},"main","5d0a87185c0e172c3901e2a6e5916b6d544b8b94","skills\u002Fgenerating-python-installer","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance","https:\u002F\u002Fgithub.com\u002FJunMystery","AI is the typist, I am the architect. Building efficient, secure, and user-centric products through disciplined AI prompt engineering.","2026-11-13 17:41:25",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add JunMystery\u002FAgent-Guidance --skill generating-python-installer",{"tool":37,"command":38},"bunx","bunx skills add JunMystery\u002FAgent-Guidance --skill generating-python-installer",{"tool":40,"command":41},"pnpm","pnpm dlx skills add JunMystery\u002FAgent-Guidance --skill generating-python-installer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fgenerating-python-installer\u002FSKILL.md",true,[],[46,52,58,64,70,76],{"skillNo":47,"name":48,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M79QR1E309VJ6CTQKB32AWWA","zero-trust-architecture-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-architecture-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M79QQV7GHYR02DYGN41S23WN","xss-filter-evasion-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxss-filter-evasion-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M79QQNSN7YB8XB61FFSCS3WH","xs-leaks-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxs-leaks-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79QQHZZJKFDY9132G5A65C2","xpath-injection-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxpath-injection-prevention-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M79QQB9ZSD3DJG8658EHQXR1","xml-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-security-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M79QQ60WKV7PFMXWT9CW8PM6","xml-external-entity-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-external-entity-prevention-cheat-sheet\u002FSKILL.md",[],[]]