Skip to content

Commit bb5e2df

Browse files
author
euper
committed
fix: 增强Python解释器路径获取和虚拟环境管理的错误处理与诊断功能
- 增强 Python 解释器路径获取逻辑,添加虚拟环境验证和错误处理机制。 - 验证Python解释器路径是否存在并在不存在时提供诊断信息和错误日志。 - 增强Python包安装功能的错误处理和诊断能力,添加Python解释器存在性验证、文件未找到异常处理和详细的错误日志记录。 - 增强虚拟环境管理器的错误处理和诊断功能,添加路径验证、详细日志输出和异常捕获机制。 - 在关于对话框和问题反馈中显示软件版本信息 - 添加检测和验证Python解释器的方法,确保在PyInstaller或Nuitka打包环境中正确识别可用的Python解释器。 Signed-off-by: euper <nginx11724@qq.com>
1 parent 2b60014 commit bb5e2df

7 files changed

Lines changed: 334 additions & 31 deletions

File tree

‎core/packager.py‎

Lines changed: 97 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,56 @@ def _set_process_callback(self, callback: Callable) -> None:
9292
self.pyinstaller_packager.set_process_callback(callback)
9393
self.nuitka_packager.set_process_callback(callback)
9494

95-
def _get_python_path(self, config: Dict) -> Optional[str]:
96-
"""获取 Python 解释器路径(不处理虚拟环境,仅获取基础解释器)"""
97-
# 优先使用配置指定的解释器
95+
def _get_python_path(self, config: Dict) -> Tuple[Optional[str], str]:
96+
"""
97+
获取 Python 解释器路径(不处理虚拟环境,仅获取基础解释器)
98+
99+
优先级:
100+
1. 用户在配置中手动指定的路径(经过有效性校验)
101+
2. 当前运行的解释器(仅在非打包环境下)
102+
3. 通过 PythonFinder 在系统中搜索
103+
104+
Returns:
105+
(python_path, error_message) 元组。
106+
成功时 python_path 为有效路径、error_message 为空字符串;
107+
失败时 python_path 为 None、error_message 为描述性错误信息。
108+
"""
109+
# 1. 优先使用配置指定的解释器
98110
python_path = config.get("python_path") or config.get("python")
99111
if python_path and os.path.exists(python_path):
100-
return python_path
101-
# 否则使用当前运行的解释器
102-
return sys.executable
112+
# 即使用户手动指定,也要验证它不是打包环境中的临时文件
113+
if PythonFinder.is_valid_python_interpreter(python_path):
114+
return python_path, ""
115+
else:
116+
self.log(f"警告: 指定的 Python 路径不是有效的解释器: {python_path}")
117+
118+
# 2. 检测是否处于 PyInstaller/Nuitka 打包后的环境中
119+
if PythonFinder.is_bundled_environment():
120+
self.log(
121+
"检测到当前运行在打包环境中,sys.executable 不可用于创建虚拟环境"
122+
)
123+
self.log(f" sys.executable = {sys.executable}")
124+
self.log("正在搜索系统中安装的 Python 解释器...")
125+
126+
finder = PythonFinder()
127+
system_python = finder.find_python()
128+
if system_python:
129+
self.log(f"✓ 找到系统 Python: {system_python}")
130+
return system_python, ""
131+
else:
132+
error_msg = (
133+
"未在系统中找到可用的 Python 解释器。\n\n"
134+
"请在工具界面的「Python路径」中手动指定系统安装的 Python 解释器路径\n"
135+
"(例如 C:\\Python311\\python.exe)。\n\n"
136+
"如果尚未安装 Python,请先从 https://www.python.org 下载安装,\n"
137+
"安装时请勾选「Add Python to PATH」。"
138+
)
139+
self.log("错误: 未在系统中找到可用的 Python 解释器")
140+
self.log("请在工具界面中手动指定 Python 路径")
141+
return None, error_msg
142+
143+
# 3. 非打包环境,使用当前解释器
144+
return sys.executable, ""
103145

104146
def _setup_venv_if_needed(
105147
self,
@@ -125,6 +167,10 @@ def _setup_venv_if_needed(
125167

126168
if not use_venv:
127169
self.log("未启用虚拟环境,使用指定的 Python 解释器")
170+
# 验证基础 Python 解释器是否存在
171+
if not os.path.exists(base_python_path):
172+
self.log(f"错误: 指定的 Python 解释器不存在: {base_python_path}")
173+
raise FileNotFoundError(f"Python 解释器不存在: {base_python_path}")
128174
return base_python_path
129175

130176
project_dir = config.get("project_dir")
@@ -140,15 +186,37 @@ def _setup_venv_if_needed(
140186
self.log("虚拟环境设置")
141187
self.log("=" * 50)
142188

189+
# 验证基础 Python 解释器路径
190+
if not os.path.exists(base_python_path):
191+
self.log(f"错误: 基础 Python 解释器不存在: {base_python_path}")
192+
self.log("将无法创建虚拟环境,请检查 Python 安装")
193+
raise FileNotFoundError(f"Python 解释器不存在: {base_python_path}")
194+
195+
self.log(f"基础 Python 解释器: {base_python_path}")
196+
143197
# 1. 检查是否存在虚拟环境
144198
existing_venv = self.venv_manager.check_existing_venv(project_dir)
199+
venv_python: Optional[str] = None
200+
active_venv_path: Optional[str] = None
145201

146202
if existing_venv:
147203
self.log(f"✓ 检测到现有虚拟环境: {existing_venv}")
148204
venv_python = self.venv_manager.get_venv_python(existing_venv)
149-
else:
205+
active_venv_path = existing_venv
206+
207+
# 验证现有虚拟环境的有效性
208+
if not os.path.exists(venv_python):
209+
self.log(f"警告: 现有虚拟环境的 Python 解释器不存在: {venv_python}")
210+
self.log("尝试验证虚拟环境...")
211+
if not self.venv_manager.validate_venv(existing_venv, verbose=True):
212+
self.log("现有虚拟环境无效,将创建新的虚拟环境")
213+
existing_venv = None
214+
venv_python = None
215+
active_venv_path = None
216+
217+
if not existing_venv:
150218
# 创建新的虚拟环境
151-
self.log("未检测到虚拟环境,正在创建...")
219+
self.log("未检测到有效的虚拟环境,正在创建...")
152220
venv_path = self.venv_manager.setup_venv(
153221
project_dir,
154222
base_python_path,
@@ -161,14 +229,29 @@ def _setup_venv_if_needed(
161229

162230
self.log(f"✓ 虚拟环境创建成功: {venv_path}")
163231
venv_python = self.venv_manager.get_venv_python(venv_path)
232+
active_venv_path = venv_path
164233

165-
# 升级 pip
166-
self.venv_manager.upgrade_pip(venv_path)
234+
# 再次验证虚拟环境是否真的可用
235+
if not os.path.exists(venv_python):
236+
self.log(f"错误: 虚拟环境创建后 Python 解释器仍不存在: {venv_python}")
237+
self.log("虚拟环境创建失败,使用原始 Python 解释器")
238+
return base_python_path
167239

168-
if not os.path.exists(venv_python):
169-
self.log("警告: 虚拟环境 Python 不存在,使用原始解释器")
240+
# 升级 pip
241+
if not self.venv_manager.upgrade_pip(venv_path):
242+
self.log("警告: pip 升级失败,但将继续使用虚拟环境")
243+
244+
# 最终验证
245+
if not venv_python or not os.path.exists(venv_python):
246+
self.log(f"错误: 虚拟环境 Python 解释器不存在: {venv_python}")
247+
self.log("详细诊断信息:")
248+
if active_venv_path:
249+
self.venv_manager.get_venv_python(active_venv_path, verify=True)
250+
self.log("回退到使用原始 Python 解释器")
170251
return base_python_path
171252

253+
self.log(f"✓ 将使用虚拟环境 Python: {venv_python}")
254+
172255
# 2. 安装依赖
173256
self._install_venv_dependencies(project_dir, venv_python, config)
174257

@@ -784,9 +867,9 @@ def package(
784867
return False, "打包已取消", None
785868

786869
# 1. 获取基础 Python 路径
787-
base_python_path = self._get_python_path(config)
870+
base_python_path, python_error = self._get_python_path(config)
788871
if not base_python_path:
789-
return False, "未找到 Python 环境", None
872+
return False, python_error or "未找到 Python 环境", None
790873

791874
self.log(f"基础 Python: {base_python_path}")
792875

‎core/packaging/dependency_installer.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,23 @@ def install_dependencies(
580580
"""
581581
self.log("\n安装项目依赖...")
582582

583+
# 验证 Python 解释器路径
584+
import os
585+
if not os.path.exists(python_path):
586+
self.log(f"错误: Python 解释器不存在,无法安装依赖")
587+
self.log(f" 路径: {python_path}")
588+
# 尝试提供诊断信息
589+
parent_dir = os.path.dirname(python_path)
590+
if os.path.exists(parent_dir):
591+
try:
592+
contents = os.listdir(parent_dir)
593+
self.log(f" 父目录存在,内容: {contents}")
594+
except Exception as e:
595+
self.log(f" 无法列出父目录内容: {e}")
596+
else:
597+
self.log(f" 父目录也不存在: {parent_dir}")
598+
return
599+
583600
if not dependencies:
584601
self.log("未发现需要安装的依赖包")
585602
return
@@ -642,6 +659,10 @@ def install_dependencies(
642659
timeout=30,
643660
creationflags=CREATE_NO_WINDOW if sys.platform == "win32" else 0,
644661
)
662+
except FileNotFoundError as e:
663+
self.log(f"警告: 升级 pip 失败 - Python 解释器不存在")
664+
self.log(f" 路径: {python_path}")
665+
self.log(f" 错误: {str(e)}")
645666
except Exception:
646667
pass # 升级失败不影响后续安装
647668

‎core/packaging/network_utils.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,24 @@ def pip_install_with_mirrors(
176176
Returns:
177177
安装是否成功
178178
"""
179+
# 验证 Python 解释器是否存在
180+
import os
181+
if not os.path.exists(python_path):
182+
self.log(f"错误: Python 解释器不存在,无法安装包")
183+
self.log(f" 路径: {python_path}")
184+
self.log(f" 包列表: {packages}")
185+
# 尝试提供诊断信息
186+
parent_dir = os.path.dirname(python_path)
187+
if os.path.exists(parent_dir):
188+
try:
189+
contents = os.listdir(parent_dir)
190+
self.log(f" 父目录内容: {contents}")
191+
except Exception as e:
192+
self.log(f" 无法列出父目录内容: {e}")
193+
else:
194+
self.log(f" 父目录也不存在: {parent_dir}")
195+
return False
196+
179197
# 获取当前网络环境对应的镜像源列表
180198
pip_mirrors = self.get_pip_mirrors()
181199

@@ -226,8 +244,17 @@ def pip_install_with_mirrors(
226244

227245
except subprocess.TimeoutExpired:
228246
self.log(f" 使用 {mirror_name} 超时")
247+
except FileNotFoundError as e:
248+
self.log(f" 使用 {mirror_name} 出错: [WinError 2] 系统找不到指定的文件。")
249+
self.log(f" Python 路径: {python_path}")
250+
self.log(f" 命令: {' '.join(cmd[:5])}...")
251+
self.log(f" 详细错误: {str(e)}")
252+
# 这是致命错误,不应继续尝试其他镜像源
253+
self.log(f"警告: 安装 {' '.join(packages)} 失败(已尝试所有镜像源)")
254+
return False
229255
except Exception as e:
230256
self.log(f" 使用 {mirror_name} 出错: {str(e)}")
257+
self.log(f" 错误类型: {type(e).__name__}")
231258

232259
# 切换到下一个镜像源
233260
self._current_mirror_index = (self._current_mirror_index + 1) % total_mirrors
@@ -237,6 +264,7 @@ def pip_install_with_mirrors(
237264
next_mirror = pip_mirrors[self._current_mirror_index][0]
238265
self.log(f" 切换到 {next_mirror}...")
239266

267+
self.log(f"警告: 安装 {' '.join(packages)} 失败(已尝试所有镜像源)")
240268
return False
241269

242270
def _get_host_from_url(self, url: str) -> str:

0 commit comments

Comments
 (0)