Python打包那些事

前言

22年的时候因为工作需要,用PySide6写了一个网络工程师工具箱,一直使用的是Nuitka静态编译的方式打包。Nuitka主要是将Python代码转换为C代码,然后进行编译,可以有效控制编译后的软件大小。

前段时间的时候突发奇想,给工具箱添加了一个插件功能,实现方式是通过importlib.util动态加载py文件中的逻辑。功能实现之后发现再用Nuitka打包就会出现问题,于是需要寻求其他的打包方式。

我的项目结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
network-toolbox/
├── main.py # 主程序入口
├── requirements.txt # 依赖列表
├── .gitignore
├── LICENSE
├── config/ # 配置文件目录
│ └── *.yaml/json
├── lib/ # 核心库文件,实现功能逻辑
│ └── *.py
├── plugins/ # 插件目录
│ └── ...
├── ui/ # UI设计文件
│ └── *.ui
├── res/ # 资源文件
│ └── ...
├── man/ # 文档目录
│ └── *.md
└── test/ # 测试文件目录

该项目对打包的需求如下:

  • 支持PySide6importlib.util
  • Windows/macOS能够直接运行,无需安装Python环境
  • 打包后的文件体积要尽可能的小
  • 由于是开源项目,对代码加密没有要求

根据网上的信息,也尝试过使用Pyinstaller,Py2app,但打包后的文件基本都在1G以上(包含完整的PySide6),并且还有各种各样的问题,最后发现PyStand的打包逻辑比较合适,遂用之。

Windows打包

PyStand的打包逻辑是使用C++为Embedded Python做了一个壳,运行这个壳时会调用Embedded Python来执行python代码,具体可以参考这个案例:

按照案例,我为项目设计了针对windows的打包目录

1
2
3
4
5
6
7
8
windows
├── appicon.ico # 图标
├── CMakeLists.txt # PyStand
├── deletion_list.txt # 需要精简的PySide6组件,减小打包后的体积
├── NEToolbox.int # 入口文件
├── PyStand.cpp # PyStand
├── PyStand.h # PyStand
└── resource.rc # PyStand

入口文件NEToolbox.int中的内容为:

1
2
3
4
5
6
import sys, os
os.chdir(os.path.dirname(__file__))
sys.path.append(os.path.abspath('script'))
sys.path.append(os.path.abspath('script.egg'))
import main
main.main()

编译PyStand和下载embedded python、依赖都由脚本完成,最后编译完成的目录结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
NEToolbox
├── NEToolbox.exe # PyStand编译的入口
├── NEToolbox.int # 入口文件
├── runtime # Embedded Python
├── script # 项目文件
│   ├── config
│   ├── lib
│   ├── LICENSE
│   ├── log
│   ├── main.py
│   ├── man
│   ├── plugins
│   ├── res
│   └── ui
└── site-packages # 依赖文件,从venv中复制

打包并精简完成后,软件体积从1G多直接降到了200多M。

macOS打包

有了Windows的打包成功经验之后,我就想macOS是否也能用同样的打包思路,但是有两个难题摆在眼前:

  1. PyStand的C代码使用了很多Windwos的API,无法直接在macOS上编译,而且作者也明确表示不会支持macOS(Issue22
  2. macOS没有官方支持的Embedded Python

所以只能自己按照PyStand的思路想办法,进过搜索之后找到了Python-Apple-support 库,这是一个专门为macOS提供嵌入式Python支持的开源项目。于是又开始折腾。

首先还是为项目设计了针对macos的打包目录

1
2
3
4
5
6
7
8
9
10
11
12
13
macos
├── Contents # macOS app包需要用到的文件,最后会复制到dist/NEToolbox.app中
│ ├── Info.plist # app信息
│ └── MacOS
│ └── NEToolbox # 启动脚本
├── deletion_list.txt # 需要精简的PySide6组件,减小打包后的体积
├── dist
│ ├── launcher # 编译生成的启动器
│ └── NEToolbox.app # 最后生成的app文件夹
├── launcher.c # 启动器源代码,按照PyStand思路编写
└── runtime # Python-Apple-support框架,不能直接运行,需要编译启动器
├── Python.xcframework
└── VERSIONS

启动脚本比较简单,主要是运行启动器:

1
2
3
4
5
6
7
8
#!/bin/bash
# NEToolbox Launcher Script
# Get the directory of the app bundle
APP_BUNDLE_DIR="$(dirname "$0")/.."
# Set the working directory to the app resources
cd "$APP_BUNDLE_DIR/Resources/"
# Run the Python application
"$APP_BUNDLE_DIR/Resources/launcher"

启动器的C代码是让AI编写的,内容如下:

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
#include <Python.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
// 初始化Python解释器
Py_Initialize();

// 设置Python模块搜索路径
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('.')");

// 执行main.py
FILE* file = fopen("main.py", "r");
if (file == NULL) {
fprintf(stderr, "无法打开main.py文件\n");
Py_Finalize();
return 1;
}

// 使用PyRun_SimpleFile执行Python脚本
int result = PyRun_SimpleFile(file, "main.py");

// 关闭文件
fclose(file);

// 关闭Python解释器
Py_Finalize();

return result;
}

编译启动器和下载embedded python、依赖都由脚本完成,最后编译完成的目录结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
NEToolbox.app
└── Contents
├── Frameworks
├── Info.plist # app信息
├── MacOS
│ └── NEToolbox # 启动脚本
└── Resources # 项目文件
├── config
├── icon.icns # 图标
├── launcher # 编译后的启动器
├── lib
├── log
├── main.py
├── man
├── plugins
├── res
├── runtime # Python-Apple-support框架
└── ui

测试运行一切OK,又找到了一个新的打包方案,最后附上打包脚本,可能无法直接使用,需要进行修改。

打包脚本

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:
# 使用sysconfig获取site-packages路径
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))

# 确保文件在PySide6目录下
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:
# 如果runtime目录已存在,先删除
if os.path.exists(extract_path):
logging.info(f"删除已存在的runtime目录:{extract_path}")
shutil.rmtree(extract_path)

# 重新创建runtime目录
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路径
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(根据系统架构选择)
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)

# 下载Python runtime
if not download_python_runtime(python_runtime_url, runtime_zip_path):
sys.exit(1)

# 解压Python runtime
if not extract_runtime(runtime_zip_path, runtime_dir):
sys.exit(1)

# 生成CMake构建文件
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框架下载URL
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)

# 创建空白DMG
subprocess.run([
'hdiutil', 'create',
'-size', '500m',
'-fs', 'HFS+',
'-volname', 'NEToolbox',
dmg_path_pre
], check=True)

# 挂载DMG
subprocess.run([
'hdiutil', 'attach',
dmg_path_pre,
'-mountpoint', mount_dir
], check=True)

# 复制NEToolbox.app到DMG
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)

# 卸载DMG
subprocess.run([
'hdiutil', 'detach',
mount_dir
], check=True)

# 压缩DMG
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路径
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)

# 检查并删除已存在的app文件夹
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)

# 下载Python runtime
if not download_python_runtime(python_runtime_url, runtime_zip_path):
sys.exit(1)

# 解压Python runtime
if not extract_runtime(runtime_zip_path, runtime_dir):
sys.exit(1)

# 编译项目
if not compile_project():
sys.exit(1)

# 读取原始Info.plist模板
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()

# 使用Jinja2渲染模板
template = Template(plist_template_str)
rendered_plist = template.render(version=version)

# 创建app目录结构
app_path = os.path.join(dist_path, 'NEToolbox.app')
os.makedirs(app_path, exist_ok=True)
logging.info(f"创建应用目录: {app_path}")

# 复制Contents目录
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和Frameworks目录
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)

# 复制文件和目录到Resources
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)

# 保存更新后的Info.plist
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()


Python打包那些事
https://www.intx.work/posts/8547414d.html
发布于
2025年7月4日
许可协议