Repository navigation
Expand file tree
/
Copy pathpackager.py
More file actions
1608 lines (1403 loc) · 62.6 KB
/
Copy pathpackager.py
File metadata and controls
1608 lines (1403 loc) · 62.6 KB
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
打包器协调模块
本模块作为打包流程的顶层协调器,负责:
- 协调各个子模块完成打包任务
- 管理打包流程的整体逻辑
- 提供统一的打包接口
子模块:
- analyzer: 依赖分析
- packaging: 打包相关工具(虚拟环境、依赖安装、图标处理、打包器等)
"""
import os
import shutil
import sys
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from core.dependency_analyzer import DependencyAnalyzer
from core.packaging.config import PackagingConfig
from core.packaging.dependency_installer import DependencyInstaller
from core.packaging.icon_processor import IconProcessor
from core.packaging.network_utils import NetworkUtils
from core.packaging.cx_freeze_packager import CxFreezePackager
from core.packaging.nuitka_packager import NuitkaPackager
from core.packaging.pipeline import PackagingPipeline
from core.packaging.pipeline_steps import (
BuildExecuteStep,
ChinesePathCheckStep,
ConfigEnhanceStep,
DataFileDetectStep,
DependencyAnalysisStep,
DependencyInstallStep,
IconInjectStep,
IconProcessingStep,
OutputDirStep,
PackagingToolInstallStep,
PythonDiscoveryStep,
QtFrameworkDetectStep,
TempCleanupStep,
VenvSetupStep,
VersionInfoStep,
VersionPostProcessStep,
)
from core.packaging.pyinstaller_packager import PyInstallerPackager
from core.packaging.venv_manager import VenvManager
from core.version_info import RceditHandler, VersionInfoHandler, WindowsResourceHandler
from utils.constants import has_chinese
from utils.dependency_manager import DependencyManager
from utils.python_finder import PythonFinder
class Packager:
"""
打包器协调类
作为高层协调器,将具体任务委托给各个子模块处理。
保持与原有接口兼容。
"""
def __init__(self):
"""初始化打包器及所有子模块"""
# 工具类
self.python_finder = PythonFinder()
self.dependency_manager = DependencyManager()
# 分析器
self.dependency_analyzer = DependencyAnalyzer()
# 打包子模块
self.venv_manager = VenvManager()
self.dependency_installer = DependencyInstaller()
self.icon_processor = IconProcessor()
self.network_utils = NetworkUtils()
self.version_info_handler = VersionInfoHandler()
self.windows_resource_handler = WindowsResourceHandler()
self.rcedit_handler = RceditHandler()
self.pyinstaller_packager = PyInstallerPackager()
self.nuitka_packager = NuitkaPackager()
self.cx_freeze_packager = CxFreezePackager()
# 回调函数
self.log: Callable = print
self.cancel_flag: Optional[Callable] = None
self.process_callback: Optional[Callable] = None
# 状态
self._last_exe_path: Optional[str] = None
# ------------------------------------------------------------------
# Pipeline 构建(新架构 — 渐进迁移中)
# ------------------------------------------------------------------
def build_pipeline(self) -> PackagingPipeline:
"""构建完整打包流水线(与传统 package() 严格等价)。
16 个 Step 对应 package() 的 12 步 + _do_package 的 5 个后处理关注点。
每个 Step 委托 Packager 的已验证方法,行为与传统路径一致。
"""
return PackagingPipeline(
[
# package() 步骤 1-11
PythonDiscoveryStep(self),
VenvSetupStep(self),
ChinesePathCheckStep(self),
OutputDirStep(self),
QtFrameworkDetectStep(self.dependency_analyzer),
DependencyAnalysisStep(self),
DependencyInstallStep(self),
PackagingToolInstallStep(self.dependency_installer),
IconProcessingStep(self),
VersionInfoStep(self),
DataFileDetectStep(self),
# package() 步骤 12(_do_package 拆解为 5 个后处理 Step)
ConfigEnhanceStep(self),
IconInjectStep(self),
BuildExecuteStep(self),
VersionPostProcessStep(self),
TempCleanupStep(self),
]
)
def package_via_pipeline(
self,
config: Dict,
log_callback: Optional[Callable] = None,
cancel_flag: Optional[Callable] = None,
process_callback: Optional[Callable] = None,
) -> Tuple[bool, str, Optional[str]]:
"""通过完整 Pipeline 执行打包(新架构主入口)。
运行 build_pipeline() 的 16 个 Step,与传统 package() 严格等价。
各 Step 委托 Packager 的已验证方法,行为一致。
"""
if log_callback:
self._set_log_callback(log_callback)
if cancel_flag:
self._set_cancel_flag(cancel_flag)
if process_callback:
self._set_process_callback(process_callback)
try:
# 规范化配置(与旧 package() 一致:PackagingConfig → dict)
if isinstance(config, PackagingConfig):
config = config.as_dict()
pipeline = self.build_pipeline()
context: Dict[str, Any] = {
"config": config,
"log": self.log,
"cancelled": self._is_cancelled,
}
result = pipeline.run(context)
success = result.get("success", False)
message = result.get("message", "")
return success, message, self._last_exe_path
except Exception as e:
self.log(f"打包异常: {e}")
import traceback
self.log(traceback.format_exc())
return False, f"打包过程出错: {str(e)}", None
def _set_log_callback(self, callback: Callable) -> None:
"""设置日志回调到所有子模块"""
self.log = callback
self.dependency_analyzer.log = callback
self.dependency_manager.log = callback
self.venv_manager.set_log_callback(callback)
self.dependency_installer.set_log_callback(callback)
self.icon_processor.set_log_callback(callback)
self.network_utils.set_log_callback(callback)
self.version_info_handler.log = callback
self.windows_resource_handler.log = callback
self.rcedit_handler.log = callback
self.pyinstaller_packager.set_log_callback(callback)
self.nuitka_packager.set_log_callback(callback)
self.cx_freeze_packager.set_log_callback(callback)
def _set_cancel_flag(self, cancel_flag: Callable) -> None:
"""设置取消标志到所有子模块"""
self.cancel_flag = cancel_flag
self.dependency_installer.set_cancel_flag(cancel_flag)
self.pyinstaller_packager.set_cancel_flag(cancel_flag)
self.nuitka_packager.set_cancel_flag(cancel_flag)
self.cx_freeze_packager.set_cancel_flag(cancel_flag)
def _set_process_callback(self, callback: Callable) -> None:
"""设置进程回调到所有子模块"""
self.process_callback = callback
self.pyinstaller_packager.set_process_callback(callback)
self.nuitka_packager.set_process_callback(callback)
self.cx_freeze_packager.set_process_callback(callback)
def _get_python_path(self, config: Dict) -> Tuple[Optional[str], str]:
"""
获取 Python 解释器路径(不处理虚拟环境,仅获取基础解释器)
优先级:
1. 用户在配置中手动指定的路径(经过有效性校验)
2. 当前运行的解释器(仅在非打包环境下)
3. 通过 PythonFinder 在系统中搜索
Returns:
(python_path, error_message) 元组。
成功时 python_path 为有效路径、error_message 为空字符串;
失败时 python_path 为 None、error_message 为描述性错误信息。
"""
# 1. 优先使用配置指定的解释器
python_path = config.get("python_path") or config.get("python")
if python_path and os.path.exists(python_path):
# 即使用户手动指定,也要验证它不是打包环境中的临时文件
if PythonFinder.is_valid_python_interpreter(python_path):
return python_path, ""
else:
self.log(f"警告: 指定的 Python 路径不是有效的解释器: {python_path}")
# 2. 检测是否处于 PyInstaller/Nuitka 打包后的环境中
if PythonFinder.is_bundled_environment():
self.log("正在搜索系统中安装的 Python 解释器...")
finder = PythonFinder()
system_python = finder.find_python()
if system_python:
self.log(f"✓ 找到系统 Python: {system_python}")
return system_python, ""
else:
error_msg = (
"未在系统中找到可用的 Python 解释器。\n\n"
"请在工具界面的「Python路径」中手动指定系统安装的 Python 解释器路径\n"
"(例如 C:\\Python311\\python.exe)。\n\n"
"如果尚未安装 Python,请先从 https://www.python.org 下载安装,\n"
"安装时请勾选「Add Python to PATH」。"
)
self.log("错误: 未在系统中找到可用的 Python 解释器")
self.log("请在工具界面中手动指定 Python 路径")
return None, error_msg
# 3. 非打包环境,使用当前解释器
return sys.executable, ""
def _setup_venv_if_needed(
self,
config: Dict,
base_python_path: str,
) -> str:
"""
根据配置设置虚拟环境
如果 use_venv 为 True:
1. 检查项目目录下是否存在虚拟环境(.venv/venv)
2. 如果不存在则创建
3. 安装依赖(从 requirements.txt 或分析项目)
Args:
config: 打包配置
base_python_path: 基础 Python 解释器路径
Returns:
最终使用的 Python 解释器路径
"""
use_venv = config.get("use_venv", False)
if not use_venv:
self.log("未启用虚拟环境,使用指定的 Python 解释器")
# 验证基础 Python 解释器是否存在
if not os.path.exists(base_python_path):
self.log(f"错误: 指定的 Python 解释器不存在: {base_python_path}")
raise FileNotFoundError(f"Python 解释器不存在: {base_python_path}")
return base_python_path
project_dir = config.get("project_dir")
if not project_dir:
script_path = config.get("script_path", "")
project_dir = os.path.dirname(script_path) if script_path else None
if not project_dir or not os.path.isdir(project_dir):
self.log("警告: 无法确定项目目录,跳过虚拟环境设置")
return base_python_path
self.log("\n" + "=" * 50)
self.log("虚拟环境设置")
self.log("=" * 50)
# 验证基础 Python 解释器路径
if not os.path.exists(base_python_path):
self.log(f"错误: 基础 Python 解释器不存在: {base_python_path}")
self.log("将无法创建虚拟环境,请检查 Python 安装")
raise FileNotFoundError(f"Python 解释器不存在: {base_python_path}")
self.log(f"基础 Python 解释器: {base_python_path}")
# 1. 检查是否存在虚拟环境
existing_venv = self.venv_manager.check_existing_venv(project_dir)
venv_python: Optional[str] = None
active_venv_path: Optional[str] = None
if existing_venv:
self.log(f"✓ 检测到现有虚拟环境: {existing_venv}")
venv_python = self.venv_manager.get_venv_python(existing_venv)
active_venv_path = existing_venv
# 验证现有虚拟环境的有效性
if not os.path.exists(venv_python):
self.log(f"警告: 现有虚拟环境的 Python 解释器不存在: {venv_python}")
self.log("尝试验证虚拟环境...")
if not self.venv_manager.validate_venv(existing_venv, verbose=True):
self.log("现有虚拟环境无效,将创建新的虚拟环境")
existing_venv = None
venv_python = None
active_venv_path = None
if not existing_venv:
# 创建新的虚拟环境
self.log("未检测到有效的虚拟环境,正在创建...")
venv_path = self.venv_manager.setup_venv(
project_dir, base_python_path, venv_name=".venv"
)
if not venv_path:
self.log("警告: 虚拟环境创建失败,使用原始 Python 解释器")
return base_python_path
self.log(f"✓ 虚拟环境创建成功: {venv_path}")
venv_python = self.venv_manager.get_venv_python(venv_path)
active_venv_path = venv_path
# 再次验证虚拟环境是否真的可用
if not os.path.exists(venv_python):
self.log(f"错误: 虚拟环境创建后 Python 解释器仍不存在: {venv_python}")
self.log("虚拟环境创建失败,使用原始 Python 解释器")
return base_python_path
# 升级 pip
if not self.venv_manager.upgrade_pip(venv_path):
self.log("警告: pip 升级失败,但将继续使用虚拟环境")
# 最终验证
if not venv_python or not os.path.exists(venv_python):
self.log(f"错误: 虚拟环境 Python 解释器不存在: {venv_python}")
self.log("详细诊断信息:")
if active_venv_path:
self.venv_manager.get_venv_python(active_venv_path, verify=True)
self.log("回退到使用原始 Python 解释器")
return base_python_path
self.log(f"✓ 将使用虚拟环境 Python: {venv_python}")
# 2. 安装依赖
self._install_venv_dependencies(project_dir, venv_python, config)
return venv_python
def _install_venv_dependencies(
self,
project_dir: str,
venv_python: str,
config: Dict,
) -> None:
"""
在虚拟环境中安装依赖
优先使用 requirements.txt,否则从项目中分析提取依赖
Args:
project_dir: 项目目录
venv_python: 虚拟环境 Python 解释器路径
config: 打包配置
"""
requirements_file = os.path.join(project_dir, "requirements.txt")
if os.path.exists(requirements_file):
# 使用 requirements.txt 安装依赖
self.log("检测到 requirements.txt,正在安装依赖...")
self._install_from_requirements(venv_python, requirements_file)
else:
# 从项目中分析依赖
self.log("未检测到 requirements.txt,正在分析项目依赖...")
script_path = config.get("script_path", "")
if script_path:
deps = self.dependency_analyzer.analyze(script_path, project_dir)
if deps:
self.log(f"检测到 {len(deps)} 个第三方依赖,正在安装...")
self._install_analyzed_dependencies(venv_python, deps, project_dir)
else:
self.log("未检测到需要安装的第三方依赖")
def _install_from_requirements(
self,
python_path: str,
requirements_file: str,
) -> bool:
"""
从 requirements.txt 安装依赖
Args:
python_path: Python 解释器路径
requirements_file: requirements.txt 文件路径
Returns:
是否成功
"""
import subprocess
from utils.constants import CREATE_NO_WINDOW
try:
# 使用镜像源安装
mirrors = [
("阿里云", "https://mirrors.aliyun.com/pypi/simple"),
("清华大学", "https://pypi.tuna.tsinghua.edu.cn/simple"),
("默认源", None),
]
for mirror_name, mirror_url in mirrors:
self.log(f" 尝试使用 {mirror_name} 安装依赖...")
cmd = [
python_path,
"-m",
"pip",
"install",
"-r",
requirements_file,
"--quiet",
]
if mirror_url:
cmd.extend(
[
"-i",
mirror_url,
"--trusted-host",
mirror_url.split("//")[1].split("/")[0],
]
)
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=300,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0:
self.log(f"✓ 依赖安装成功(使用 {mirror_name})")
return True
else:
self.log(f" {mirror_name} 安装失败,尝试下一个镜像源...")
except subprocess.TimeoutExpired:
self.log(f" {mirror_name} 安装超时,尝试下一个镜像源...")
self.log("警告: 所有镜像源均安装失败")
return False
except Exception as e:
self.log(f"安装依赖时出错: {e}")
return False
def _install_analyzed_dependencies(
self,
python_path: str,
deps: set,
project_dir: str,
) -> bool:
"""
安装分析到的依赖
Args:
python_path: Python 解释器路径
deps: 依赖集合
project_dir: 项目目录
Returns:
是否成功
"""
# 获取内部模块信息
internal_modules = getattr(
self.dependency_analyzer, "_project_internal_modules", set()
)
is_stdlib = self.dependency_analyzer._is_stdlib
is_internal = getattr(self.dependency_analyzer, "_is_internal_module", None)
result = self.dependency_installer.install_dependencies(
python_path,
deps,
project_dir,
internal_modules,
is_stdlib,
is_internal,
)
return result if result is not None else True
def _is_cancelled(self) -> bool:
"""检查是否已取消"""
return self.cancel_flag is not None and self.cancel_flag()
def _has_chinese(self, text: str) -> bool:
"""检查字符串中是否包含 CJK 表意文字(委托 utils.constants.has_chinese)。
覆盖基本区 (U+4E00-U+9FFF) 及扩展 A/B/C-F 区,能识别生僻字、姓名用字。
"""
return has_chinese(text)
def _check_chinese_paths(self, config: Dict) -> None:
"""检查路径中是否包含中文字符并发出警告"""
script_path = config.get("script_path")
project_dir = config.get("project_dir")
paths_to_check = {
"脚本路径": script_path,
"项目目录": project_dir,
}
chinese_paths = []
for path_name, path_value in paths_to_check.items():
if path_value and self._has_chinese(path_value):
chinese_paths.append(f"{path_name}: {path_value}")
if chinese_paths:
self.log("\n" + "!" * 50)
self.log("警告: 检测到路径中包含中文字符")
self.log("!" * 50)
for path_info in chinese_paths:
self.log(f" {path_info}")
self.log("")
self.log("中文路径可能导致以下问题:")
self.log(" 1. PyInstaller/Nuitka 在处理某些依赖时可能出现编码错误")
self.log(" 2. 虚拟环境创建可能失败")
self.log(" 3. Qt 插件目录识别可能出现问题")
self.log("")
self.log("建议:")
self.log(" - 将项目移动到纯英文路径下(如 C:/Projects/myapp)")
self.log("")
self.log("打包将继续尝试,但可能会遇到问题...")
self.log("!" * 50 + "\n")
@staticmethod
def _get_protected_dirs() -> List[str]:
"""
获取受保护的系统目录列表
这些目录中的内容不得被自动清空,以防止误删用户重要文件。
返回的路径均经过规范化处理,大小写不敏感比较时应注意平台差异。
Returns:
受保护目录的绝对路径列表
"""
protected = []
home = os.path.expanduser("~")
# Windows 特殊目录
if sys.platform == "win32":
# 桌面
desktop = os.path.join(home, "Desktop")
if os.path.exists(desktop):
protected.append(os.path.normpath(desktop))
# 用户主目录本身
protected.append(os.path.normpath(home))
# 系统盘根目录
system_drive = os.environ.get("SystemDrive", "C:")
protected.append(os.path.normpath(system_drive + os.sep))
# 常见用户目录
for folder in [
"Downloads",
"Documents",
"Pictures",
"Videos",
"Music",
"OneDrive",
"AppData",
".ssh",
".git",
]:
path = os.path.join(home, folder)
if os.path.exists(path):
protected.append(os.path.normpath(path))
# Windows 系统目录
windir = os.environ.get("WINDIR", "C:\\Windows")
if os.path.exists(windir):
protected.append(os.path.normpath(windir))
# Program Files 目录
for pf in ["Program Files", "Program Files (x86)"]:
pf_path = os.path.join(os.environ.get("SystemDrive", "C:") + os.sep, pf)
if os.path.exists(pf_path):
protected.append(os.path.normpath(pf_path))
else:
# Linux / macOS 系统目录
protected.append(os.path.normpath(home))
for folder in [
"Desktop",
"Downloads",
"Documents",
"Pictures",
"/",
"/etc",
"/usr",
"/bin",
"/sbin",
"/var",
"/tmp",
]:
path = folder if folder.startswith("/") else os.path.join(home, folder)
if os.path.exists(path):
protected.append(os.path.normpath(path))
return protected
@staticmethod
def _is_protected_dir(dir_path: str) -> Tuple[bool, str]:
"""
检查目录是否为受保护的系统目录
Args:
dir_path: 要检查的目录路径
Returns:
(是否为受保护目录, 匹配到的受保护目录路径)
"""
normalized = os.path.normpath(os.path.abspath(dir_path)).rstrip(os.sep)
normalized_lower = normalized.lower()
for protected in Packager._get_protected_dirs():
protected_norm = os.path.normpath(protected).rstrip(os.sep)
if normalized_lower == protected_norm.lower():
return True, protected_norm
return False, ""
@staticmethod
def _is_safe_output_dir(
output_dir: str, script_path: str, project_dir: Optional[str]
) -> Tuple[bool, str]:
"""
检查输出目录是否安全(不会被误删重要文件)
Args:
output_dir: 输出目录路径
script_path: 脚本路径
project_dir: 项目目录
Returns:
(是否安全, 错误信息/空字符串表示安全)
"""
normalized = os.path.normpath(os.path.abspath(output_dir))
# 1. 检查是否直接是受保护目录
is_protected, matched = Packager._is_protected_dir(normalized)
if is_protected:
return False, (
f"输出目录 '{output_dir}' 是受保护的系统目录 "
f"({matched})。\n"
f"请选择一个项目子目录或专门的构建输出目录,"
f"以避免误删重要文件。"
)
# 2. 检查输出目录是否在受保护目录的父级中
# (防止 output_dir = C:\ 这种根目录情况)
normalized_lower = normalized.lower()
for protected in Packager._get_protected_dirs():
protected_norm = os.path.normpath(protected).rstrip(os.sep).lower()
# 如果输出目录是受保护目录的祖先(受保护目录在输出目录内部),
# 且输出目录层级较浅(如根目录),则也认为是危险的
if (
protected_norm.startswith(normalized_lower + os.sep)
and normalized_lower.count(os.sep) <= 1
):
return False, (
f"输出目录 '{output_dir}' 层级过浅,"
f"且包含了系统目录 '{protected}'。\n"
f"请选择一个更具体的子目录(如项目下的 build 目录),"
f"以确保不会误删重要文件。"
)
# 3. 如果 output_dir 的目录名不是 "build" 或类似构建目录名,发出提醒
# (这只是一个宽松的检查,不宜过于严格)
dir_basename = os.path.basename(normalized.rstrip(os.sep)).lower()
script_dir = os.path.normpath(os.path.dirname(os.path.abspath(script_path)))
project_root = (
os.path.normpath(os.path.abspath(project_dir))
if project_dir
else script_dir
)
# 如果输出目录不在脚本目录或项目目录下,且不是 build/dist/out 等构建目录
build_like_names = {
"build",
"dist",
"output",
"out",
"target",
"bin",
"__pycache__",
".build",
".dist",
}
if dir_basename not in build_like_names:
# 检查是否在项目目录范围内
if (
not normalized_lower.startswith(project_root.lower() + os.sep)
and normalized_lower != project_root.lower()
):
# 不在项目目录下,给出警告但仍允许使用
# (不阻止,因为用户可能有合理的自定义输出目位置)
pass
return True, ""
def _prepare_output_dir(self, config: Dict) -> str:
"""准备输出目录"""
script_path = config["script_path"]
project_dir = config.get("project_dir")
output_dir = config.get("output_dir")
if not output_dir:
if project_dir:
output_dir = os.path.join(project_dir, "build")
else:
output_dir = os.path.join(os.path.dirname(script_path), "build")
# 安全校验:防止输出目录为受保护的系统目录
is_safe, error_msg = self._is_safe_output_dir(
output_dir, script_path, project_dir
)
if not is_safe:
raise ValueError(error_msg)
# 精准清理与本次构建相关的旧产物
if os.path.exists(output_dir):
self.log(f"\n检测到已存在的输出目录: {output_dir}")
try:
# 推导本次构建涉及的名称
script_stem = Path(script_path).stem
program_name = (
config.get("program_name")
or (os.path.basename(project_dir) if project_dir else None)
or script_stem
)
# 构建需要清理的精准模式
# 1. Nuitka 以入口脚本名命名的中间目录
target_dirs = [
f"{script_stem}.build",
f"{script_stem}.dist",
f"{script_stem}.onefile-build",
]
# 如果 program_name 与 script_stem 不同,也清理以 program_name 命名的目录
if program_name and program_name != script_stem:
target_dirs += [
f"{program_name}.build",
f"{program_name}.dist",
f"{program_name}.onefile-build",
]
# 2. 上次输出的 exe
target_files = []
if program_name:
target_files.append(f"{program_name}.exe")
target_files.append(f"{script_stem}.exe")
# 3. 构建日志和临时图标
target_files += [
"build.log",
"icon_converted.ico",
]
cleaned = 0
failed: List[str] = []
# 关键产物(exe)清理失败需要用户介入的标识
critical_exe_names = {f"{program_name}.exe"} if program_name else set()
critical_exe_names.add(f"{script_stem}.exe")
for name in target_dirs:
path = os.path.join(output_dir, name)
if os.path.isdir(path):
try:
shutil.rmtree(path)
self.log(f" 已清理: {name}/")
cleaned += 1
except Exception as clean_err:
failed.append(name + "/")
self.log(f" ⚠️ 清理失败: {name}/ ({clean_err})")
for name in set(target_files): # set 去重
path = os.path.join(output_dir, name)
if os.path.isfile(path):
try:
os.unlink(path)
self.log(f" 已清理: {name}")
cleaned += 1
except Exception as clean_err:
failed.append(name)
self.log(f" ⚠️ 清理失败: {name} ({clean_err})")
if cleaned and not failed:
self.log(f"✓ 旧构建文件已清理(共 {cleaned} 项)")
elif cleaned and failed:
self.log(
f"✓ 已清理 {cleaned} 项;但 {len(failed)} 项失败: {', '.join(failed)}"
)
elif not failed:
self.log("✓ 无需清理")
# 关键 exe 未清理 → 可能是上次打包的 exe 正在运行
critical_failed = [f for f in failed if f in critical_exe_names]
if critical_failed:
self.log("!" * 50)
self.log(
f"警告: 关键产物无法删除: {', '.join(critical_failed)}"
)
self.log(" 可能原因:上一次打包的 exe 仍在运行(被占用)。")
self.log(" 请关闭正在运行的程序后重试,否则可能打包出含旧代码的 exe。")
self.log("!" * 50)
except Exception as e:
self.log(f"警告:清理输出目录时出错: {str(e)}")
os.makedirs(output_dir, exist_ok=True)
return output_dir
def _analyze_dependencies(
self,
script_path: str,
project_dir: Optional[str],
python_path: str,
config: Dict,
) -> Tuple[set, List[str], List[str]]:
"""
分析项目依赖
Returns:
(dependencies, hidden_imports, exclude_modules)
"""
self.log("\n" + "=" * 50)
self.log("第一阶段:依赖分析")
self.log("=" * 50)
# 静态分析
self.log("执行静态依赖分析...")
deps = self.dependency_analyzer.analyze(script_path, project_dir)
self.log(f"静态分析检测到 {len(deps)} 个第三方依赖")
if deps:
# 显示具体的依赖名称
deps_list = sorted(deps)
self.log(f" 依赖列表: {', '.join(deps_list)}")
# 动态追踪(非 GUI 项目)
self.log("执行动态导入追踪...")
success_trace, traced = self.dependency_analyzer.trace_dynamic_imports(
script_path, python_path, project_dir
)
if success_trace:
self.log(f"动态追踪捕获到 {len(traced)} 个导入")
# 自动分析第三方库的子模块(未命中加速缓存的库)
self.dependency_analyzer.collect_third_party_submodules(python_path)
# 获取优化建议并自动应用到配置
exclude_modules, hidden_imports, _ = (
self.dependency_analyzer.get_optimization_suggestions(python_path)
)
# 自动合并到配置中的 hidden_imports / exclude_modules(去重保序)
config_hidden = config.get("hidden_imports", []) or []
config_exclude = config.get("exclude_modules", []) or []
merged_hidden = list(dict.fromkeys(config_hidden + hidden_imports))
merged_exclude = list(dict.fromkeys(config_exclude + exclude_modules))
config["hidden_imports"] = merged_hidden
config["exclude_modules"] = merged_exclude
applied_hidden_count = max(0, len(merged_hidden) - len(config_hidden))
applied_exclude_count = max(0, len(merged_exclude) - len(config_exclude))
self.log(
f"已自动应用隐藏导入: +{applied_hidden_count} 个(当前共 {len(merged_hidden)} 个)"
)
self.log(
f"已自动应用排除模块: +{applied_exclude_count} 个(当前共 {len(merged_exclude)} 个)"
)
return deps, merged_hidden, merged_exclude
def _install_dependencies(
self,
python_path: str,
deps: set,
project_dir: Optional[str],
) -> bool:
"""安装项目依赖"""
self.log("\n" + "=" * 50)
self.log("第二阶段:依赖安装")
self.log("=" * 50)
# 获取内部模块信息
internal_modules = getattr(
self.dependency_analyzer, "_project_internal_modules", set()
)
is_stdlib = self.dependency_analyzer._is_stdlib
is_internal = getattr(self.dependency_analyzer, "_is_internal_module", None)
self.dependency_installer.install_dependencies(
python_path,
deps,
project_dir,
internal_modules,
is_stdlib,
is_internal,
)
return True
def _process_icon(
self,
config: Dict,
output_dir: str,
python_path: str,
) -> Optional[str]:
"""处理图标文件"""
# 同时支持 "icon" 和 "icon_path" 两个键名(兼容GUI和其他调用方式)
icon_path = config.get("icon") or config.get("icon_path")
if not icon_path:
self.log("\n未指定程序图标,将使用默认图标")
return None
self.log("\n处理图标文件...")
self.log(f" 用户指定的图标路径: {icon_path}")
# 验证图标文件是否存在
if not os.path.exists(icon_path):
self.log(f" ⚠️ 警告: 图标文件不存在: {icon_path}")
return None
# 输出图标文件信息
try:
icon_size = os.path.getsize(icon_path)
icon_ext = os.path.splitext(icon_path)[1].lower()
self.log(f" 图标文件大小: {icon_size} 字节, 格式: {icon_ext}")
except Exception as e:
self.log(f" 无法获取图标文件信息: {e}")
processed_icon, warnings = self.icon_processor.process_icon_file(
icon_path, output_dir, python_path
)
for warning in warnings:
self.log(f" 图标: {warning}")
if processed_icon:
self.log(f" 最终使用的图标文件: {processed_icon}")
else:
self.log(" 图标处理失败,将使用默认图标")
return processed_icon
def _prepare_version_info(self, config: Dict, output_dir: str) -> Optional[str]:
"""准备版本信息"""
# 检查是否有版本信息配置
# GUI 将版本信息存储在 config["version_info"] 嵌套字典中
version_info = config.get("version_info")
if version_info:
self.log(f"\n检测到版本信息配置: {list(version_info.keys())}")
has_version_info = any(
[
version_info.get("version"),
version_info.get("company_name"),
version_info.get("file_description"),
version_info.get("copyright"),
version_info.get("product_name"),
]
)
else:
self.log("\n未检测到 config['version_info'] 嵌套字典,尝试检查顶层键...")
# 兼容:也检查顶层键(以防其他调用方式)
has_version_info = any(
[
config.get("version"),
config.get("company_name"),
config.get("file_description"),
config.get("copyright"),
]
)
if not has_version_info:
self.log("未找到任何版本信息字段,跳过版本信息处理")
return None
self.log("\n准备版本信息...")
version_file = self._create_version_info_file(config, output_dir)
if version_file: