Files
pricing_review/build_portable.py

201 lines
8.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""构建单机便携版(方案 B:embeddable Python + bat,2026-10-07 主人定)。
与旧 PyInstaller 路线的区别:
· 主执行文件 = python.org 官方签名的 python.exe(embeddable 包)→ 杀软误报率大幅降低;
· 升级 = 替换 造价审核\app 目录,运行时不用重发;
· 空库分发:测试数据不再出门,目标机首次运行自动建表。
用法(在开发机上,需可访问 python.org;有本地缓存则离线可用):
python build_portable.py # 构建 + 冒烟(服务 200 + 隐藏窗口初始化)
产物:release/PricingReview-Windows-x64/(目录,可直接拷贝)与同名 .zip。
"""
import io
import os
import pathlib
import shutil
import subprocess
import sys
import urllib.request
import zipfile
ROOT = pathlib.Path(__file__).resolve().parent
NAME = "PricingReview-Windows-x64"
OUT = ROOT / "release"
PACKAGE = OUT / NAME
APP = ROOT / "造价审核" / "app"
# 与开发环境同大版本的 embeddable 包(多备几个补丁号,第一个能下载的胜出)
EMBED_VERSIONS = ["3.13.9", "3.13.11", "3.13.12", "3.13.14", "3.13.5", "3.13.2"]
DEPS = ["pywebview==6.2.1", "openpyxl==3.1.5", "xlrd==2.0.1"]
BAT_GUI = (
"@echo off\r\n"
"cd /d \"%~dp0\"\r\n"
"echo 正在启动造价审核窗口,请稍候...\r\n"
"\"%~dp0python\\python.exe\" \"%~dp0launch.py\"\r\n"
"if errorlevel 1 pause\r\n"
)
BAT_ADMIN = (
"@echo off\r\n"
"cd /d \"%~dp0\"\r\n"
"echo 正在启动后台服务,请稍候...\r\n"
"\"%~dp0python\\python.exe\" \"%~dp0launch.py\" admin\r\n"
"echo.\r\n"
"echo 关闭这个黑窗口 = 停止服务。\r\n"
"pause\r\n"
)
README = r"""造价审核 · 单机便携版
========================
启动
· 双击「启动造价审核.bat」:弹出软件窗口(审核工作台);
· 双击「启动后台管理.bat」:用浏览器打开后台管理(关闭黑窗口 = 停止服务)。
要求
· Windows 10/11 64 位;
· 独立窗口需要 Microsoft Edge WebView2 运行库(多数系统自带;缺失时软件会提示并
引导安装,也可直接用浏览器模式)。下载页:
https://developer.microsoft.com/microsoft-edge/webview2/
· 不需要安装 Python 或任何其他组件。
数据
· 全部数据存在「造价审核\data」文件夹里(数据库 + 上传的文件)。
· 拷贝/搬家:关掉软件后把整个文件夹一起拷走。
· 本包为空库:首次启动自动建表,从零开始录入。
排错
· 窗口/页面起不来时,用终端运行 bat 看报错;把 造价审核\data\launch.log 一并带给维护人。
"""
def log(msg):
print(msg, flush=True)
def fetch_embeddable(cache_dir):
"""取 embeddable zip:先看本地缓存,没有就按候选版本从 python.org 下载。"""
cache_dir.mkdir(parents=True, exist_ok=True)
for ver in EMBED_VERSIONS:
cached = cache_dir / ("python-%s-embed-amd64.zip" % ver)
if cached.is_file() and cached.stat().st_size > 1_000_000:
log("使用缓存 %s" % cached.name)
return cached
url = "https://www.python.org/ftp/python/%s/python-%s-embed-amd64.zip" % (ver, ver)
try:
log("下载 %s …" % url)
req = urllib.request.Request(url, headers={"User-Agent": "pricing-review-build"})
with urllib.request.urlopen(req, timeout=60) as r, open(cached, "wb") as f:
f.write(r.read())
if cached.stat().st_size > 1_000_000:
return cached
except Exception as e:
log(" 失败:%s" % e)
if cached.exists():
cached.unlink()
raise RuntimeError(
"embeddable 包取不到:请手动下载 python-3.13.x-embed-amd64.zip 放到 %s" % cache_dir)
def write_gbk(path, text):
"""bat 红线:GBK + CRLF;中文路径一律经 %~dp0 / 英文名脚本,不写死在 bat 里。"""
with open(path, "w", encoding="gbk", newline="") as f:
f.write(text)
def main():
if os.name != "nt":
raise RuntimeError("请在 Windows x64 上构建")
build_py = pathlib.Path(sys.executable)
OUT.mkdir(exist_ok=True)
if PACKAGE.exists():
log("清理旧包 %s" % PACKAGE)
shutil.rmtree(PACKAGE)
PACKAGE.mkdir(parents=True)
# 1) embeddable 运行时 → python/,启用 site-packages
z = fetch_embeddable(OUT / "_cache")
py_dir = PACKAGE / "python"
log("解压运行时 → python/")
with zipfile.ZipFile(z) as zf:
zf.extractall(py_dir)
pth = py_dir / "python313._pth"
if pth.is_file():
io.open(pth, "w", encoding="ascii", newline="\n").write(
"python313.zip\n.\nLib\\site-packages\n")
else:
raise RuntimeError("解包结果里没有 python313._pth,embeddable 版本变了?")
# 2) 依赖装进包内 site-packages(用构建机的 pip 解析版本,与开发环境一致)
sp = py_dir / "Lib" / "site-packages"
log("安装依赖 → python/Lib/site-packages")
subprocess.run([str(build_py), "-m", "pip", "install", "--target", str(sp),
"--upgrade", "--no-warn-script-location"] + DEPS, check=True)
# 3) 应用代码 + 空数据目录 + 启动器
app_target = PACKAGE / "造价审核" / "app"
shutil.copytree(APP, app_target,
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"), dirs_exist_ok=True)
data = PACKAGE / "造价审核" / "data"
for folder in ("", "uploads", "attachments", "inquiry"):
(data / folder).mkdir(parents=True, exist_ok=True)
shutil.copy2(ROOT / "launch.py", PACKAGE / "launch.py")
write_gbk(PACKAGE / "启动造价审核.bat", BAT_GUI)
write_gbk(PACKAGE / "启动后台管理.bat", BAT_ADMIN)
(PACKAGE / "使用说明.txt").write_text(README, encoding="utf-8-sig")
# 4) 冒烟:① 空库起服务 → 页面 200 → 有表;② 隐藏窗口初始化(验 WebView2/pythonnet)
env = dict(os.environ, PR_PORT="8399")
log("冒烟①:空库起服务(PR_PORT=8399)…")
smoke = subprocess.run(
[str(py_dir / "python.exe"), "-c",
"import os,sys,time,urllib.request\n"
"sys.path.insert(0,'server'); sys.path.insert(0,'core'); sys.path.insert(0,'.')\n"
"import api_server\n"
"import threading; threading.Thread(target=api_server.run, daemon=True).start()\n"
"ok=False\n"
"for _ in range(40):\n"
" try:\n"
" r=urllib.request.urlopen('http://127.0.0.1:8399/admin.html',timeout=1)\n"
" if r.status==200: ok=True; break\n"
" except Exception: time.sleep(0.25)\n"
"assert ok, 'admin.html 不返回 200'\n"
"import json\n"
"d=json.loads(urllib.request.urlopen('http://127.0.0.1:8399/api/admin/summary',timeout=5).read())\n"
"print('SMOKE-SERVER-OK stale=', d.get('stale'))\n"],
cwd=app_target, env=env, capture_output=True, text=True, timeout=120)
if smoke.returncode != 0 or "SMOKE-SERVER-OK" not in (smoke.stdout or ""):
raise RuntimeError("服务冒烟失败:\n%s\n%s" % (smoke.stdout, smoke.stderr))
log(smoke.stdout.strip())
log("冒烟②:隐藏窗口初始化(WebView2 / pythonnet)…")
smoke2 = subprocess.run(
[str(py_dir / "python.exe"), "-c",
"import sys, threading, time\n"
"import webview\n"
"win = webview.create_window('smoke', 'http://127.0.0.1:1/notused', hidden=True)\n"
"t = threading.Thread(target=lambda: webview.start(debug=False), daemon=True)\n"
"t.start()\n"
"time.sleep(4)\n"
"print('SMOKE-WINDOW-OK')\n"
"os._exit(0)\n"],
cwd=app_target, env=env, capture_output=True, text=True, timeout=60)
if "SMOKE-WINDOW-OK" not in (smoke2.stdout or ""):
log("⚠ 窗口冒烟未通过(目标机将走浏览器兜底):\n%s\n%s" % (smoke2.stdout, smoke2.stderr))
else:
log(smoke2.stdout.strip())
# 5) 打 zip
archive = OUT / (NAME + ".zip")
log("打包 %s …" % archive.name)
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
for f in PACKAGE.rglob("*"):
if f.is_file():
zf.write(f, pathlib.Path(NAME) / f.relative_to(PACKAGE))
safe = str(archive).encode("ascii", "backslashreplace").decode("ascii")
log("完成:%s(目录 %s)" % (safe, PACKAGE))
if __name__ == "__main__":
main()