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 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
| import os, sys, subprocess, sysconfig, shutil, platform import logging, json, zipfile, ssl import urllib.request from jinja2 import Template ssl._create_default_https_context = ssl._create_unverified_context def get_site_packages_path(): """获取当前Python环境的site-packages路径""" try: site_packages_path = sysconfig.get_paths()['purelib'] logging.info(f"Site-packages路径: {site_packages_path}") return site_packages_path except Exception as e: logging.error(f"获取site-packages路径失败: {e}") return None
def get_version(): global project_root config_path = os.path.join(project_root, 'config', 'build.json') try: with open(config_path, 'r') as f: config = json.load(f) version = config.get('version', '1.0') return version except Exception as e: logging.error(f"读取版本号失败: {e}")
def cleanup_pyside6_files(workdir, site_packages_path): """ 读取deletion_list.txt并删除PySide6目录中的指定文件和空目录 :param site_packages_path: site-packages目录路径 :return: 成功删除的文件数量 """ deletion_list_path = os.path.join(workdir, 'deletion_list.txt') pyside6_path = os.path.join(site_packages_path, 'PySide6') try: with open(deletion_list_path, 'r', encoding='utf-8') as f: files_to_delete = [line.strip() for line in f if line.strip()] deleted_count = 0 for relative_path in files_to_delete: full_path = os.path.normpath(os.path.join(pyside6_path, relative_path)) if not full_path.startswith(pyside6_path): logging.warning(f"跳过不安全的路径: {full_path}") continue try: if os.path.isfile(full_path): os.unlink(full_path) deleted_count += 1 logging.info(f"已删除文件: {full_path}") except FileNotFoundError: logging.warning(f"文件不存在: {full_path}") except PermissionError: logging.error(f"无权删除文件: {full_path}") for root, dirs, files in os.walk(pyside6_path, topdown=False): for dir_name in dirs: dir_path = os.path.join(root, dir_name) try: if not os.listdir(dir_path): os.rmdir(dir_path) logging.info(f"已删除空目录: {dir_path}") except OSError: pass logging.info(f"清理完成,共删除 {deleted_count} 个文件") return deleted_count except FileNotFoundError: logging.error(f"未找到文件: {deletion_list_path}") return 0 except Exception as e: logging.error(f"清理PySide6文件时发生错误: {e}") return 0
def setup_logging(log_path): """设置日志记录""" logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s', handlers=[ logging.FileHandler(log_path, encoding='utf-8'), logging.StreamHandler(sys.stdout) ] ) return logging.getLogger(__name__)
def check_tools(): """检查必要的编译工具""" try: subprocess.run(['cmake', '--version'], capture_output=True, text=True) except FileNotFoundError: logging.error("未找到CMake。请确保CMake已安装并添加到系统PATH") return False return True
def download_python_runtime(url, download_path): """下载Python runtime""" if os.path.exists(download_path): logging.info(f"Python runtime文件已存在:{download_path}") return True
try: logging.info(f"开始下载Python runtime: {url}") def progress_hook(block_num, block_size, total_size): downloaded = block_num * block_size percent = min(int(downloaded * 100 / total_size), 100) if total_size > 0 else 0 sys.stdout.write(f"\r下载进度: {percent}%") sys.stdout.flush() urllib.request.urlretrieve(url, download_path, reporthook=progress_hook) logging.info("\nPython runtime下载完成") return True except Exception as e: logging.error(f"下载Python runtime失败: {e}") return False
def extract_runtime(zip_path:str, extract_path): """解压Python runtime""" try: if os.path.exists(extract_path): logging.info(f"删除已存在的runtime目录:{extract_path}") shutil.rmtree(extract_path) os.makedirs(extract_path, exist_ok=True) logging.info("开始解压Python runtime") if zip_path.endswith(".zip"): with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_path) elif zip_path.endswith(".tar.gz"): subprocess.run([ "tar", "-xzf", zip_path, "-C", extract_path ], check=True) logging.info("Python runtime解压完成") return True except Exception as e: logging.error(f"解压Python runtime失败: {e}") return False
def copy_file(source, dest, files_to_copy=[]): for src, dst in files_to_copy: src_path = os.path.join(source, src) dst_path = os.path.join(dest, dst) if dst else os.path.join(dest, src) try: if os.path.isdir(src_path): logging.info(f"复制目录: {src_path} -> {dst_path}") shutil.copytree(src_path, dst_path, symlinks=True, dirs_exist_ok=True) else: logging.info(f"复制文件: {src_path} -> {dst_path}") shutil.copy2(src_path, dst_path) except Exception as e: logging.error(f"复制失败: {e}")
def get_system_arch(): """ 动态获取系统架构 :return: 系统架构字符串 """ machine = platform.machine().lower() if machine in ['amd64', 'x86_64']: return 'amd64' elif machine in ['arm64', 'aarch64']: return 'arm64' else: return machine
def build_on_windows(workdir): runtime_dir = os.path.join(workdir, 'runtime') dist_dir = os.path.join(workdir, 'dist') app_dir = os.path.join(workdir, 'dist', 'NEToolbox') build_dir = os.path.join(workdir, 'build') site_packages_path = get_site_packages_path()
def generate_cmake_files(): """使用CMake生成构建文件""" try: logging.info("开始生成CMake构建文件") subprocess.run([ 'cmake', '-G', 'MinGW Makefiles', f'-B{build_dir}', f'-S{workdir}' ], check=True) return True except subprocess.CalledProcessError as e: logging.error(f"CMake构建文件生成失败: {e}") return False def compile_project(): """使用CMake编译项目""" try: logging.info("开始编译项目") result = subprocess.run([ 'cmake', '--build', build_dir, '--config', 'Release' ], capture_output=True, text=True, check=False) if result.returncode != 0: logging.error(f"项目编译失败,返回码:{result.returncode}") logging.error("标准输出:" + result.stdout) logging.error("标准错误:" + result.stderr) return False return True except Exception as e: logging.error(f"编译过程发生异常: {e}") return False def create_zip_package(): """ 创建zip打包 :param dist_dir: 发布目录 """ try: arch = get_system_arch() global version zip_filename = f'NEToolbox_windows_{arch}_v{version}.zip' zip_path = os.path.join(dist_dir, zip_filename) logging.info(f"开始创建zip包:{zip_filename}") with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(os.path.join(dist_dir, 'NEToolbox')): for file in files: file_path = os.path.join(root, file) arcname = os.path.relpath(file_path, dist_dir) zipf.write(file_path, arcname=arcname) logging.info(f"zip包创建成功:{zip_path}") except Exception as e: logging.error(f"创建zip包失败: {e}") for directory in [dist_dir, build_dir]: if os.path.exists(directory): logging.info(f"删除已存在的目录:{directory}") shutil.rmtree(directory) os.makedirs(directory)
os.makedirs(runtime_dir, exist_ok=True) os.makedirs(app_dir, exist_ok=True) python_runtime_url = 'https://www.python.org/ftp/python/3.13.4/python-3.13.4-embed-amd64.zip' runtime_zip_path = os.path.join(workdir, 'python_runtime.zip') if not check_tools(): logger.error("必要工具检查失败") sys.exit(1) if not download_python_runtime(python_runtime_url, runtime_zip_path): sys.exit(1) if not extract_runtime(runtime_zip_path, runtime_dir): sys.exit(1) if not generate_cmake_files(): sys.exit(1) if not compile_project(): sys.exit(1) try: shutil.copy2( os.path.join(build_dir, 'PyStand.exe'), os.path.join(app_dir, 'NEToolbox.exe') ) logger.info(f"编译全部完成!可执行文件已生成:{app_dir}/NEToolbox.exe") except Exception as e: logger.error(f"可执行文件复制失败: {e}") sys.exit(1) files_to_copy = [ ('res', 'script/res'), ('lib', 'script/lib'), ('config', 'script/config'), ('man', 'script/man'), ('plugins', 'script/plugins'), ('ui', 'script/ui'), ('main.py', 'script/main.py'), ('package/windows/runtime', 'runtime'), ('package/windows/NEToolbox.int', 'NEToolbox.int'), ] logger.info(f"开始复制项目文件") copy_file(project_root, app_dir, files_to_copy) packagess_to_copy = [ ('_distutils_hack', ''), ('_yaml', ''), ('yaml', ''), ('distutils-precedence.pth', ''), ('markupsafe', ''), ] requirements = ["et_xmlfile", "jinja2", "MarkupSafe", "openpyxl", "PySide6", "PyYAML", "shiboken6"] listdir = os.listdir(site_packages_path) for pkg in requirements: dirname = [_ for _ in listdir if _.startswith(pkg)] packagess_to_copy.extend(list(zip(dirname, dirname))) dist_site_packages_path = os.path.join(app_dir, "site-packages") logger.info(f"开始复制依赖文件") os.makedirs(dist_site_packages_path, exist_ok=True) copy_file(site_packages_path, dist_site_packages_path, packagess_to_copy) logger.info(f"开始精简Pyside6") cleanup_pyside6_files(workdir, dist_site_packages_path) create_zip_package()
def package_macos_app(workdir): global project_root, version runtime_dir = os.path.join(workdir, 'runtime') dist_path = os.path.join(workdir, 'dist') app_dist_path = os.path.join(dist_path, 'NEToolbox.app') python_runtime_url="https://github.com/beeware/Python-Apple-support/releases/download/3.13-b9/Python-3.13-macOS-support.b9.tar.gz" runtime_zip_path = os.path.join(workdir, 'python_framework.tar.gz') python_framework = "runtime/Python.xcframework/macos-arm64_x86_64/Python.framework" python_lib = f"{python_framework}/Versions/3.13/lib"
def compile_project(): logger.info("开始编译Python运行时...") if not os.path.exists(os.path.join(workdir, python_framework)): logger.error("Python框架不存在,无法编译") return False result = subprocess.run([ 'clang', '-o', f'{dist_path}/launcher', f'launcher.c', '-I', f'{python_framework}/Headers', '-F', f'{python_framework}/..', '-framework', 'Python', f'-Wl,-rpath,{python_framework}/..', '-L', f'{python_lib}', '-lpython3.13', '-ldl' ], capture_output=True, text=True, check=False, cwd=workdir) if result.returncode != 0: logging.error(f"项目编译失败,返回码:{result.returncode}") logging.error("标准输出:" + result.stdout) logging.error("标准错误:" + result.stderr) return False return True def create_dmg(): """ 创建DMG镜像,包含NEToolbox.app和应用程序文件夹的替身 :param dist_path: 发布目录路径 :param version: 应用版本 """ try: dmg_filename_pre = f'NEToolbox_macos_pre.dmg' dmg_filename = f'NEToolbox_macos_{get_system_arch()}_v{version}.dmg' dmg_path_pre = os.path.join(dist_path, dmg_filename_pre) dmg_path = os.path.join(dist_path, dmg_filename) mount_dir = os.path.join(dist_path, 'dmg_mount') os.makedirs(mount_dir, exist_ok=True) subprocess.run([ 'hdiutil', 'create', '-size', '500m', '-fs', 'HFS+', '-volname', 'NEToolbox', dmg_path_pre ], check=True) subprocess.run([ 'hdiutil', 'attach', dmg_path_pre, '-mountpoint', mount_dir ], check=True) app_path = os.path.join(dist_path, 'NEToolbox.app') subprocess.run([ 'cp', '-R', app_path, os.path.join(mount_dir, 'NEToolbox.app') ], check=True) subprocess.run([ 'ln', '-s', '/Applications', os.path.join(mount_dir, 'Applications') ], check=True) subprocess.run([ 'hdiutil', 'detach', mount_dir ], check=True) subprocess.run([ 'hdiutil', 'convert', dmg_path_pre, '-format', 'UDZO', '-o', dmg_path ], check=True) logging.info(f"成功创建DMG镜像:{dmg_filename}") except subprocess.CalledProcessError as e: logging.error(f"创建DMG镜像失败: {e}") except Exception as e: logging.error(f"创建DMG镜像时发生异常: {e}") finally: try: logging.info(f"清理环境...") os.rmdir(mount_dir) os.remove(dmg_path_pre) except: pass
site_packages_path = get_site_packages_path() for directory in [dist_path, runtime_dir]: if os.path.exists(directory): logging.info(f"删除已存在的目录:{directory}") shutil.rmtree(directory) os.makedirs(directory) if os.path.exists(app_dist_path): logging.info(f"删除已存在的app文件夹: {app_dist_path}") shutil.rmtree(app_dist_path)
if not check_tools(): logger.error("必要工具检查失败") sys.exit(1) if not download_python_runtime(python_runtime_url, runtime_zip_path): sys.exit(1) if not extract_runtime(runtime_zip_path, runtime_dir): sys.exit(1) if not compile_project(): sys.exit(1) plist_path = os.path.join(workdir, 'Contents', 'Info.plist') logging.info(f"读取Info.plist: {plist_path}") with open(plist_path, 'r') as f: plist_template_str = f.read() template = Template(plist_template_str) rendered_plist = template.render(version=version) app_path = os.path.join(dist_path, 'NEToolbox.app') os.makedirs(app_path, exist_ok=True) logging.info(f"创建应用目录: {app_path}") contents_src = os.path.join(workdir, 'Contents') contents_dst = os.path.join(app_path, 'Contents') logging.info(f"复制Contents目录: {contents_src} -> {contents_dst}") shutil.copytree(contents_src, contents_dst, dirs_exist_ok=True) resources_path = os.path.join(app_path, 'Contents', 'Resources') frameworks_path = os.path.join(app_path, 'Contents', 'Frameworks') os.makedirs(resources_path, exist_ok=True) os.makedirs(frameworks_path, exist_ok=True) logging.info(f"创建Resources目录: {resources_path}") logging.info(f"创建Frameworks目录: {frameworks_path}") packagess_to_copy = [ ('_distutils_hack', ''), ('_yaml', ''), ('yaml', ''), ('distutils-precedence.pth', ''), ('markupsafe', ''), ] requirements = ["et_xmlfile", "jinja2", "MarkupSafe", "openpyxl", "PySide6", "PyYAML", "shiboken6"] listdir = os.listdir(site_packages_path) for pkg in requirements: dirname = [_ for _ in listdir if _.startswith(pkg)] packagess_to_copy.extend(list(zip(dirname, dirname))) dist_site_packages_path = os.path.join(workdir, python_lib, "python3.13", "site-packages") logger.info(f"开始复制依赖文件") os.makedirs(dist_site_packages_path, exist_ok=True) copy_file(site_packages_path, dist_site_packages_path, packagess_to_copy) logger.info(f"开始精简Pyside6") cleanup_pyside6_files(workdir, dist_site_packages_path)
files_to_copy = [ ('res/icon.icns', 'icon.icns'), ('res', 'res'), ('lib', 'lib'), ('config', 'config'), ('man', 'man'), ('plugins', 'plugins'), ('ui', 'ui'), ('main.py', 'main.py'), ('package/macos/runtime', 'runtime'), ('package/macos/dist/launcher', 'launcher') ] logger.info(f"开始复制项目文件") copy_file(project_root, resources_path, files_to_copy) plist_dst = os.path.join(app_path, 'Contents', 'Info.plist') logging.info(f"保存更新后的Info.plist: {plist_dst}") with open(plist_dst, 'w') as f: f.write(rendered_plist) logging.info(f"成功打包 NEToolbox.app 版本 {version}") logging.info(f"开始创建dmg镜像") create_dmg()
def main(): global project_root, logger, version script_dir = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.abspath(os.path.join(script_dir, '..')) log_path = os.path.join(script_dir, 'compile.log') logger = setup_logging(log_path) system = platform.system().lower() version = get_version() logger.info(f"当前系统架构为: {system}") logging.info(f"当前版本号: {version}") match system: case "windows": workdir = os.path.join(script_dir, "windows") build_on_windows(workdir) case "darwin": workdir = os.path.join(script_dir, "macos") package_macos_app(workdir) case _: logger.error("系统架构不匹配,无法编译")
if __name__ == '__main__': main()
|