Repository navigation
Expand file tree
/
Copy pathpython_finder.py
More file actions
326 lines (279 loc) · 11.2 KB
/
Copy pathpython_finder.py
File metadata and controls
326 lines (279 loc) · 11.2 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
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Optional
from utils.constants import CREATE_NO_WINDOW
class PythonFinder:
"""Python环境查找工具"""
def __init__(self):
self.python_path = None
@staticmethod
def is_bundled_environment() -> bool:
"""
检测当前是否运行在 PyInstaller/Nuitka 打包后的环境中
PyInstaller 单文件模式运行时,sys.executable 指向临时目录中的
bundled python.exe,该文件不是完整的 Python 解释器,不能用于
创建虚拟环境或执行 pip 操作。
Returns:
True 表示当前处于打包环境中
"""
# PyInstaller 设置的标志属性
if getattr(sys, "frozen", False):
return True
# PyInstaller 单文件模式的临时解压目录标志
if getattr(sys, "_MEIPASS", None):
return True
# Nuitka 编译后的标志
if "__compiled__" in dir():
return True
# 检测 sys.executable 是否在临时目录中(PyInstaller 单文件模式特征)
try:
exe_path = os.path.normpath(sys.executable)
temp_dir = os.path.normpath(tempfile.gettempdir())
if exe_path.startswith(temp_dir):
return True
except Exception:
pass
return False
@staticmethod
def is_valid_python_interpreter(python_path: str) -> bool:
"""
检测给定的 Python 路径是否是一个可用于打包的完整 Python 解释器
排除以下情况:
- PyInstaller 临时目录中的 bundled python.exe
- 不存在的路径
- 无法执行 'python -c "import venv"' 的解释器
Args:
python_path: Python 解释器路径
Returns:
True 表示是有效的完整 Python 解释器
"""
if not python_path or not os.path.exists(python_path):
return False
# 检查是否在临时目录中(PyInstaller 单文件解压目录)
try:
exe_path = os.path.normpath(python_path)
temp_dir = os.path.normpath(tempfile.gettempdir())
if exe_path.startswith(temp_dir):
return False
except Exception:
pass
# 检查是否能执行基本的 Python 命令,并且有 venv 模块
try:
result = subprocess.run(
[python_path, "-c", "import venv; import pip; print('ok')"],
capture_output=True,
text=True,
timeout=10,
creationflags=CREATE_NO_WINDOW,
)
return result.returncode == 0
except Exception:
return False
def find_python(self) -> Optional[str]:
"""
查找系统中的Python安装路径
搜索优先级(Windows):
1. 当前运行的 Python(非打包环境)
2. PATH 环境变量
3. pyenv-win shims → versions(活动版本 → 字母序最新)
4. 常见安装路径 + 注册表
Returns:
Python可执行文件的路径,未找到则返回None
"""
# 1. 尝试使用当前运行的Python(仅在非打包环境下)
if not self.is_bundled_environment():
current_python = sys.executable
if current_python and os.path.exists(current_python):
if self._verify_python(current_python):
self.python_path = current_python
return current_python
# 2. 尝试从PATH环境变量查找
path_python = self._find_in_path()
if path_python:
self.python_path = path_python
return path_python
# 3. Windows特定路径查找(含 pyenv-win)
if sys.platform == "win32":
windows_python = self._find_in_windows()
if windows_python:
self.python_path = windows_python
return windows_python
return None
def _verify_python(self, python_path: str) -> bool:
"""验证Python路径是否有效"""
try:
result = subprocess.run(
[python_path, "--version"],
capture_output=True,
text=True,
timeout=5,
creationflags=CREATE_NO_WINDOW,
)
return result.returncode == 0
except Exception:
return False
def _find_in_path(self) -> Optional[str]:
"""从PATH环境变量中查找Python"""
try:
# Windows
if sys.platform == "win32":
result = subprocess.run(
["where", "python"],
capture_output=True,
text=True,
creationflags=CREATE_NO_WINDOW,
)
# Unix-like
else:
result = subprocess.run(
["which", "python3"],
capture_output=True,
text=True,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode != 0:
result = subprocess.run(
["which", "python"],
capture_output=True,
text=True,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0:
python_path = result.stdout.strip().split("\n")[0]
if os.path.exists(python_path) and self._verify_python(python_path):
return python_path
except Exception:
pass
return None
def _find_in_windows(self) -> Optional[str]:
"""在Windows系统中查找Python"""
# 1. 检测 pyenv-win shims(优先)
pyenv_root = Path.home() / ".pyenv" / "pyenv-win"
shim_bat = pyenv_root / "shims" / "python.bat"
if shim_bat.exists():
# 解析 python.bat 找到真实的 python.exe 路径
try:
content = shim_bat.read_text(encoding="utf-8", errors="ignore")
for line in content.splitlines():
line = line.strip()
if "python.exe" in line and not line.startswith("@"):
# 提取引号中的路径
import re
match = re.search(r'"([^"]+python\.exe)"', line)
if match:
python_path = match.group(1)
if os.path.exists(python_path) and self._verify_python(
python_path
):
return python_path
except Exception:
pass
# 2. 检测 pyenv-win versions 目录
versions_dir = pyenv_root / "versions"
if versions_dir.exists():
# 优先使用 version 文件记录的活动版本
version_file = pyenv_root / "version"
if version_file.exists():
try:
active_version = version_file.read_text().strip()
python_exe = versions_dir / active_version / "python.exe"
if python_exe.exists() and self._verify_python(str(python_exe)):
return str(python_exe)
except Exception:
pass
# 回退:字母序最新的版本目录
try:
versions = sorted(
[d for d in versions_dir.iterdir() if d.is_dir()],
key=lambda d: d.name,
reverse=True,
)
for ver_dir in versions:
python_exe = ver_dir / "python.exe"
if python_exe.exists() and self._verify_python(str(python_exe)):
return str(python_exe)
except Exception:
pass
# 3. 常见的Windows Python安装路径
common_paths = [
Path(os.environ.get("LOCALAPPDATA", "")) / "Programs" / "Python",
Path(os.environ.get("PROGRAMFILES", "")) / "Python",
Path(os.environ.get("PROGRAMFILES(X86)", "")) / "Python",
Path("C:/") / "Python",
]
# 搜索Python版本目录
for base_path in common_paths:
if not base_path.exists():
continue
# 查找Python3x目录
try:
for item in base_path.iterdir():
if item.is_dir() and item.name.startswith("Python3"):
python_exe = item / "python.exe"
if python_exe.exists() and self._verify_python(str(python_exe)):
return str(python_exe)
except Exception:
continue
# 4. 尝试从注册表查找(Windows)
try:
import winreg
python_path = self._find_in_registry(winreg)
if python_path:
return python_path
except ImportError:
pass
return None
def _find_in_registry(self, winreg) -> Optional[str]:
"""从Windows注册表查找Python"""
registry_paths = [
(winreg.HKEY_CURRENT_USER, r"Software\Python\PythonCore"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\Python\PythonCore"),
]
for hkey, subkey in registry_paths:
try:
key = winreg.OpenKey(hkey, subkey)
num_subkeys = winreg.QueryInfoKey(key)[0]
# 遍历所有Python版本
versions = []
for i in range(num_subkeys):
try:
version = winreg.EnumKey(key, i)
versions.append(version)
except Exception:
continue
# 按版本号排序,优先使用最新版本
versions.sort(reverse=True)
for version in versions:
try:
install_path_key = winreg.OpenKey(
key, rf"{version}\InstallPath"
)
install_path = winreg.QueryValue(install_path_key, "")
python_exe = os.path.join(install_path, "python.exe")
if os.path.exists(python_exe) and self._verify_python(
python_exe
):
return python_exe
except Exception:
continue
except Exception:
continue
return None
def get_python_version(self, python_path: str) -> Optional[str]:
"""获取Python版本信息"""
try:
result = subprocess.run(
[python_path, "--version"],
capture_output=True,
text=True,
timeout=5,
creationflags=CREATE_NO_WINDOW,
)
if result.returncode == 0:
return result.stdout.strip() or result.stderr.strip()
except Exception:
pass
return None