# -*- coding: utf-8 -*- """一键打包:图标 → PyInstaller → 补齐资源 → Inno Setup 安装包 用法(在项目根目录): python build_exe.py 正常打包(含安装包) python build_exe.py --clean 先删 build/ dist/ 再打包 python build_exe.py --no-installer 只出程序目录,不做安装包 产物: dist\\入库分拣工作站\\入库分拣工作站.exe ← 程序目录(onedir) dist\\入库分拣工作站_安装程序_v1.0.29.exe ← 现场只拷这一个 安装包会装到 C:\\入库分拣工作站(可在安装时改),带桌面快捷方式、 开始菜单、卸载项,目标机不需要装 Python 或任何运行库。 """ import os import shutil import subprocess import sys ROOT = os.path.dirname(os.path.abspath(__file__)) APP_NAME = '入库分拣工作站' APP_VERSION = '1.0.76' ASSETS = os.path.join(ROOT, 'assets') DIST = os.path.join(ROOT, 'dist') OUT = os.path.join(DIST, APP_NAME) ISCC_CANDIDATES = [ r'C:\Program Files (x86)\Inno Setup 6\ISCC.exe', r'C:\Program Files\Inno Setup 6\ISCC.exe', os.path.expandvars(r'%LOCALAPPDATA%\Programs\Inno Setup 6\ISCC.exe'), ] # ------------------------------------------------------------------ 图标 def make_icon(path): """画一枚 256×256 的 ico:深蓝底 + 白色纸箱 + 橙色对勾""" try: from PIL import Image, ImageDraw except Exception as e: # noqa: BLE001 print(' [跳过图标] Pillow 不可用: %s' % e) return False S = 1024 im = Image.new('RGBA', (S, S), (0, 0, 0, 0)) d = ImageDraw.Draw(im) # 底板(圆角方块,现场图标风格) d.rounded_rectangle([0, 0, S - 1, S - 1], radius=int(S * 0.22), fill=(22, 82, 160, 255)) d.rounded_rectangle([0, int(S * 0.62), S - 1, S - 1], radius=int(S * 0.22), fill=(18, 68, 134, 255)) # 纸箱 d.rounded_rectangle([int(S * 0.17), int(S * 0.20), int(S * 0.70), int(S * 0.63)], radius=int(S * 0.035), fill=(247, 250, 253, 255)) # 箱盖折缝 + 中缝(用底色描出,表示封箱) d.line([int(S * 0.17), int(S * 0.30), int(S * 0.70), int(S * 0.30)], fill=(190, 208, 228, 255), width=int(S * 0.018)) d.line([int(S * 0.435), int(S * 0.20), int(S * 0.435), int(S * 0.63)], fill=(190, 208, 228, 255), width=int(S * 0.022)) # 秤台 d.rounded_rectangle([int(S * 0.10), int(S * 0.66), int(S * 0.90), int(S * 0.755)], radius=int(S * 0.03), fill=(247, 250, 253, 255)) d.rounded_rectangle([int(S * 0.30), int(S * 0.755), int(S * 0.70), int(S * 0.80)], radius=int(S * 0.012), fill=(150, 176, 205, 255)) # 橙色对勾徽标 d.ellipse([int(S * 0.55), int(S * 0.52), int(S * 0.98), int(S * 0.95)], fill=(255, 152, 0, 255)) w = int(S * 0.045) d.line([int(S * 0.655), int(S * 0.735), int(S * 0.735), int(S * 0.815)], fill=(255, 255, 255, 255), width=w, joint='curve') d.line([int(S * 0.735), int(S * 0.815), int(S * 0.885), int(S * 0.655)], fill=(255, 255, 255, 255), width=w, joint='curve') os.makedirs(os.path.dirname(path), exist_ok=True) sizes = [(256, 256), (128, 128), (64, 64), (48, 48), (32, 32), (16, 16)] im.resize((256, 256), Image.LANCZOS).save( path, format='ICO', sizes=sizes) return True _V4 = tuple(([int(x) for x in APP_VERSION.split('.')] + [0, 0, 0])[:4]) _V4S = '.'.join(str(x) for x in _V4) VERSION_TXT = """VSVersionInfo( ffi=FixedFileInfo(filevers=%s, prodvers=%s, mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1, subtype=0x0, date=(0, 0)), kids=[ StringFileInfo([StringTable('080404B0', [ StringStruct('CompanyName', '配送中心'), StringStruct('FileDescription', '入库分拣工作站'), StringStruct('FileVersion', '%s'), StringStruct('InternalName', 'WeighStation'), StringStruct('OriginalFilename', '入库分拣工作站.exe'), StringStruct('ProductName', '入库分拣工作站'), StringStruct('ProductVersion', '%s'), StringStruct('LegalCopyright', '内部使用')])]), VarFileInfo([VarStruct('Translation', [2052, 1200])]) ] ) """ % (_V4, _V4, _V4S, _V4S) # ------------------------------------------------------------------ 资源补齐 def copy_resources(): """把现场需要看的/需要改的文件放到 exe 同目录(不塞进包内)""" os.makedirs(OUT, exist_ok=True) pairs = [ (os.path.join(ASSETS, 'config.default.json'), os.path.join(OUT, 'config.json')), (os.path.join(ROOT, '使用说明.txt'), os.path.join(OUT, '使用说明.txt')), ] for src, dst in pairs: if os.path.exists(src): shutil.copy2(src, dst) print(' + %s' % os.path.basename(dst)) # data/photos:卡片兜底图片(没有也不影响,只是卡片右上角空白) src_dir = os.path.join(ROOT, 'data', 'photos') dst_dir = os.path.join(OUT, 'data', 'photos') if os.path.isdir(src_dir): os.makedirs(dst_dir, exist_ok=True) n = 0 for fn in os.listdir(src_dir): if fn.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')): shutil.copy2(os.path.join(src_dir, fn), os.path.join(dst_dir, fn)) n += 1 print(' + data/photos/ (%d 张)' % n) # models/cls:本地识别模型(有就带上,installer.iss 的 # 「Source: {#SrcDir}\models\cls\*」只认 dist 目录,源码树里的模型 # 不搬过来那行永远命中不到,装出来就没有本地模型。 # 没有也不阻塞打包:秤端登录后会自动从后台下载(见 tools/sync_cls_model.py)。 src_cls = os.path.join(ROOT, 'models', 'cls') dst_cls = os.path.join(OUT, 'models', 'cls') if os.path.isdir(src_cls): os.makedirs(dst_cls, exist_ok=True) n = 0 for fn in ('product_cls.onnx', 'classes.json', 'model.json'): sp = os.path.join(src_cls, fn) if os.path.isfile(sp): shutil.copy2(sp, os.path.join(dst_cls, fn)) n += 1 if n: print(' + models/cls/ (%d 个文件)' % n) else: print(' [提示] models/cls 里没有模型三件套,本次不打包模型') else: print(' [提示] 无 models/cls,安装包不含本地模型(登录后自动下载)') for sub in ('data/journal', 'data/snapshots', 'data/thumb_cache'): os.makedirs(os.path.join(OUT, sub), exist_ok=True) def dir_size(path): total = 0 for base, _dirs, files in os.walk(path): for fn in files: try: total += os.path.getsize(os.path.join(base, fn)) except OSError: pass return total # ------------------------------------------------------------------ 安装包 def find_iscc(): for p in ISCC_CANDIDATES: if os.path.exists(p): return p for base in os.environ.get('PATH', '').split(os.pathsep): p = os.path.join(base, 'ISCC.exe') if base and os.path.exists(p): return p return '' def build_installer(): """调 Inno Setup 打成一个安装包(依赖全都装进去,目标是双击即装即用)""" iscc = find_iscc() if not iscc: print(' [跳过] 没找到 Inno Setup 的 ISCC.exe') print(' 安装:winget install JRSoftware.InnoSetup') print(' 或到 https://jrsoftware.org/isdl.php 下载安装后重跑') return '' vc = os.path.join(ROOT, 'build_assets', 'vc_redist.x64.exe') if not os.path.exists(vc): print(' [提示] 缺 build_assets\\vc_redist.x64.exe,安装包不含运行库兜底') cmd = [iscc, '/DAppVersion=%s' % APP_VERSION, os.path.join(ROOT, 'installer.iss')] rc = subprocess.call(cmd, cwd=ROOT) if rc != 0: print(' [失败] ISCC 返回 %d,安装包未生成' % rc) return '' out = os.path.join(DIST, '%s_安装程序_v%s.exe' % (APP_NAME, APP_VERSION)) return out if os.path.exists(out) else '' def main(): clean = '--clean' in sys.argv print('=' * 58) print(' 入库分拣工作站 · 打包') print('=' * 58) print('[1/5] 生成图标与版本信息 …') make_icon(os.path.join(ASSETS, 'app.ico')) with open(os.path.join(ASSETS, 'version_info.txt'), 'w', encoding='utf-8') as f: f.write(VERSION_TXT) if clean: print('[2/5] 清理旧的 build/ dist/ …') for d in ('build', 'dist'): p = os.path.join(ROOT, d) if os.path.isdir(p): shutil.rmtree(p, ignore_errors=True) else: print('[2/5] 保留旧构建(增量)') print('[3/5] PyInstaller 打包(首次 2~5 分钟,请等它跑完)…') cmd = [sys.executable, '-m', 'PyInstaller', '--noconfirm', os.path.join(ROOT, 'main.spec')] rc = subprocess.call(cmd, cwd=ROOT) if rc != 0: print('\n[失败] PyInstaller 返回 %d,看上面的报错。' % rc) return rc if not os.path.exists(os.path.join(OUT, APP_NAME + '.exe')): print('\n[失败] 没找到 %s.exe,打包未产出。' % APP_NAME) return 2 print('[4/5] 补齐配置文件 / 使用说明 / 图片 …') copy_resources() size = dir_size(OUT) / 1024 / 1024 print('[5/5] 生成安装包(Inno Setup)…') setup = '' if '--no-installer' not in sys.argv: setup = build_installer() print('\n打包完成:%s' % OUT) print(' 程序目录 %.1f MB 启动:双击 %s.exe' % (size, APP_NAME)) if setup: print(' 安装包 %s(%.1f MB)' % (setup, os.path.getsize(setup) / 1024 / 1024)) print(' 现场只需这一个文件:双击 → 下一步 → 完成') else: print(' 分发:整个文件夹一起拷(不能只拷 exe)') return 0 if __name__ == '__main__': sys.exit(main())