python-discovery 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,222 @@
1
+ """Implement https://www.python.org/dev/peps/pep-0514/ to discover interpreters - Windows only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import sys
9
+ import winreg
10
+ from logging import basicConfig, getLogger
11
+ from typing import TYPE_CHECKING, Any, Final
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Generator
15
+
16
+ _RegistrySpec = tuple[str, int | None, int | None, int, bool, str, str | None]
17
+
18
+ _LOGGER: Final[logging.Logger] = getLogger(__name__)
19
+ _ARCH_RE: Final[re.Pattern[str]] = re.compile(
20
+ r"""
21
+ ^
22
+ (\d+) # bitness number
23
+ bit # literal suffix
24
+ $
25
+ """,
26
+ re.VERBOSE,
27
+ )
28
+ _VERSION_RE: Final[re.Pattern[str]] = re.compile(
29
+ r"""
30
+ ^
31
+ (\d+) # major
32
+ (?:\.(\d+))? # optional minor
33
+ (?:\.(\d+))? # optional micro
34
+ $
35
+ """,
36
+ re.VERBOSE,
37
+ )
38
+ _THREADED_TAG_RE: Final[re.Pattern[str]] = re.compile(
39
+ r"""
40
+ ^
41
+ \d+ # major
42
+ (\.\d+){0,2} # optional minor/micro
43
+ t # free-threaded flag
44
+ $
45
+ """,
46
+ re.VERBOSE | re.IGNORECASE,
47
+ )
48
+
49
+
50
+ def enum_keys(key: Any) -> Generator[str, None, None]: # noqa: ANN401
51
+ at = 0
52
+ while True:
53
+ try:
54
+ yield winreg.EnumKey(key, at) # ty: ignore[unresolved-attribute]
55
+ except OSError:
56
+ break
57
+ at += 1
58
+
59
+
60
+ def get_value(key: Any, value_name: str | None) -> Any: # noqa: ANN401
61
+ try:
62
+ return winreg.QueryValueEx(key, value_name)[0] # ty: ignore[unresolved-attribute]
63
+ except OSError:
64
+ return None
65
+
66
+
67
+ def discover_pythons() -> Generator[_RegistrySpec, None, None]:
68
+ for hive, hive_name, key, flags, default_arch in [
69
+ (winreg.HKEY_CURRENT_USER, "HKEY_CURRENT_USER", r"Software\Python", 0, 64), # ty: ignore[unresolved-attribute]
70
+ (winreg.HKEY_LOCAL_MACHINE, "HKEY_LOCAL_MACHINE", r"Software\Python", winreg.KEY_WOW64_64KEY, 64), # ty: ignore[unresolved-attribute]
71
+ (winreg.HKEY_LOCAL_MACHINE, "HKEY_LOCAL_MACHINE", r"Software\Python", winreg.KEY_WOW64_32KEY, 32), # ty: ignore[unresolved-attribute]
72
+ ]:
73
+ yield from process_set(hive, hive_name, key, flags, default_arch)
74
+
75
+
76
+ def process_set(
77
+ hive: int,
78
+ hive_name: str,
79
+ key: str,
80
+ flags: int,
81
+ default_arch: int,
82
+ ) -> Generator[_RegistrySpec, None, None]:
83
+ try:
84
+ with winreg.OpenKeyEx(hive, key, 0, winreg.KEY_READ | flags) as root_key: # ty: ignore[unresolved-attribute]
85
+ for company in enum_keys(root_key):
86
+ if company == "PyLauncher": # reserved
87
+ continue
88
+ yield from process_company(hive_name, company, root_key, default_arch)
89
+ except OSError:
90
+ pass
91
+
92
+
93
+ def process_company(
94
+ hive_name: str,
95
+ company: str,
96
+ root_key: Any, # noqa: ANN401
97
+ default_arch: int,
98
+ ) -> Generator[_RegistrySpec, None, None]:
99
+ with winreg.OpenKeyEx(root_key, company) as company_key: # ty: ignore[unresolved-attribute]
100
+ for tag in enum_keys(company_key):
101
+ spec = process_tag(hive_name, company, company_key, tag, default_arch)
102
+ if spec is not None:
103
+ yield spec
104
+
105
+
106
+ def process_tag(hive_name: str, company: str, company_key: Any, tag: str, default_arch: int) -> _RegistrySpec | None: # noqa: ANN401
107
+ with winreg.OpenKeyEx(company_key, tag) as tag_key: # ty: ignore[unresolved-attribute]
108
+ version = load_version_data(hive_name, company, tag, tag_key)
109
+ if version is not None: # if failed to get version bail
110
+ major, minor, _ = version
111
+ arch = load_arch_data(hive_name, company, tag, tag_key, default_arch)
112
+ if arch is not None:
113
+ exe_data = load_exe(hive_name, company, company_key, tag)
114
+ if exe_data is not None:
115
+ exe, args = exe_data
116
+ threaded = load_threaded(hive_name, company, tag, tag_key)
117
+ return company, major, minor, arch, threaded, exe, args
118
+ return None
119
+ return None
120
+ return None
121
+
122
+
123
+ def load_exe(hive_name: str, company: str, company_key: Any, tag: str) -> tuple[str, str | None] | None: # noqa: ANN401
124
+ key_path = f"{hive_name}/{company}/{tag}"
125
+ try:
126
+ with winreg.OpenKeyEx(company_key, rf"{tag}\InstallPath") as ip_key, ip_key: # ty: ignore[unresolved-attribute]
127
+ exe = get_value(ip_key, "ExecutablePath")
128
+ if exe is None:
129
+ ip = get_value(ip_key, None)
130
+ if ip is None:
131
+ msg(key_path, "no ExecutablePath or default for it")
132
+
133
+ else:
134
+ exe = os.path.join(ip, "python.exe")
135
+ if exe is not None and os.path.exists(exe):
136
+ args = get_value(ip_key, "ExecutableArguments")
137
+ return exe, args
138
+ msg(key_path, f"could not load exe with value {exe}")
139
+ except OSError:
140
+ msg(f"{key_path}/InstallPath", "missing")
141
+ return None
142
+
143
+
144
+ def load_arch_data(hive_name: str, company: str, tag: str, tag_key: Any, default_arch: int) -> int | None: # noqa: ANN401
145
+ arch_str = get_value(tag_key, "SysArchitecture")
146
+ if arch_str is not None:
147
+ key_path = f"{hive_name}/{company}/{tag}/SysArchitecture"
148
+ try:
149
+ return parse_arch(arch_str)
150
+ except ValueError as sys_arch:
151
+ msg(key_path, sys_arch)
152
+ return default_arch
153
+
154
+
155
+ def parse_arch(arch_str: Any) -> int: # noqa: ANN401
156
+ if isinstance(arch_str, str):
157
+ if match := _ARCH_RE.match(arch_str):
158
+ return int(next(iter(match.groups())))
159
+ error = f"invalid format {arch_str}"
160
+ else:
161
+ error = f"arch is not string: {arch_str!r}"
162
+ raise ValueError(error)
163
+
164
+
165
+ def load_version_data(
166
+ hive_name: str,
167
+ company: str,
168
+ tag: str,
169
+ tag_key: Any, # noqa: ANN401
170
+ ) -> tuple[int | None, int | None, int | None] | None:
171
+ for candidate, key_path in [
172
+ (get_value(tag_key, "SysVersion"), f"{hive_name}/{company}/{tag}/SysVersion"),
173
+ (tag, f"{hive_name}/{company}/{tag}"),
174
+ ]:
175
+ if candidate is not None:
176
+ try:
177
+ return parse_version(candidate)
178
+ except ValueError as sys_version:
179
+ msg(key_path, sys_version)
180
+ return None
181
+
182
+
183
+ def parse_version(version_str: Any) -> tuple[int | None, int | None, int | None]: # noqa: ANN401
184
+ if isinstance(version_str, str):
185
+ if match := _VERSION_RE.match(version_str):
186
+ g1, g2, g3 = match.groups()
187
+ return (
188
+ int(g1) if g1 is not None else None,
189
+ int(g2) if g2 is not None else None,
190
+ int(g3) if g3 is not None else None,
191
+ )
192
+ error = f"invalid format {version_str}"
193
+ else:
194
+ error = f"version is not string: {version_str!r}"
195
+ raise ValueError(error)
196
+
197
+
198
+ def load_threaded(hive_name: str, company: str, tag: str, tag_key: Any) -> bool: # noqa: ANN401
199
+ display_name = get_value(tag_key, "DisplayName")
200
+ if display_name is not None:
201
+ if isinstance(display_name, str):
202
+ if "freethreaded" in display_name.lower():
203
+ return True
204
+ else:
205
+ key_path = f"{hive_name}/{company}/{tag}/DisplayName"
206
+ msg(key_path, f"display name is not string: {display_name!r}")
207
+ return bool(_THREADED_TAG_RE.match(tag))
208
+
209
+
210
+ def msg(path: str, what: object) -> None:
211
+ _LOGGER.warning("PEP-514 violation in Windows Registry at %s error: %s", path, what)
212
+
213
+
214
+ def _run() -> None:
215
+ basicConfig()
216
+ interpreters = [repr(spec) for spec in discover_pythons()]
217
+ sys.stdout.write("\n".join(sorted(interpreters)))
218
+ sys.stdout.write("\n")
219
+
220
+
221
+ if __name__ == "__main__":
222
+ _run()
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from python_discovery._py_info import PythonInfo
6
+ from python_discovery._py_spec import PythonSpec
7
+
8
+ from ._pep514 import discover_pythons
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Generator, Mapping
12
+
13
+ from python_discovery._cache import PyInfoCache
14
+
15
+ _IMPLEMENTATION_BY_ORG: dict[str, str] = {
16
+ "ContinuumAnalytics": "CPython",
17
+ "PythonCore": "CPython",
18
+ }
19
+
20
+
21
+ class Pep514PythonInfo(PythonInfo):
22
+ """A Python information acquired from PEP-514."""
23
+
24
+
25
+ def propose_interpreters(
26
+ spec: PythonSpec,
27
+ cache: PyInfoCache | None,
28
+ env: Mapping[str, str],
29
+ ) -> Generator[PythonInfo, None, None]:
30
+ existing = list(discover_pythons())
31
+ existing.sort(
32
+ key=lambda i: (
33
+ *tuple(-1 if j is None else j for j in i[1:4]),
34
+ 1 if i[0] == "PythonCore" else 0,
35
+ ),
36
+ reverse=True,
37
+ )
38
+
39
+ for name, major, minor, arch, threaded, exe, _ in existing:
40
+ implementation = _IMPLEMENTATION_BY_ORG.get(name, name)
41
+
42
+ skip_pre_filter = implementation.lower() != "cpython"
43
+ registry_spec = PythonSpec("", implementation, major, minor, None, arch, exe, free_threaded=threaded)
44
+ if skip_pre_filter or registry_spec.satisfies(spec):
45
+ interpreter = Pep514PythonInfo.from_exe(exe, cache, env=env, raise_on_error=False)
46
+ if interpreter is not None and interpreter.satisfies(spec, impl_must_match=True):
47
+ yield interpreter
48
+
49
+
50
+ __all__ = [
51
+ "Pep514PythonInfo",
52
+ "propose_interpreters",
53
+ ]
File without changes
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-discovery
3
+ Version: 1.0.0
4
+ Summary: Python interpreter discovery
5
+ Project-URL: Changelog, https://github.com/tox-dev/python-discovery/releases
6
+ Project-URL: Documentation, https://python-discovery.readthedocs.io
7
+ Project-URL: Homepage, https://github.com/tox-dev/python-discovery
8
+ Project-URL: Source, https://github.com/tox-dev/python-discovery
9
+ Project-URL: Tracker, https://github.com/tox-dev/python-discovery/issues
10
+ Maintainer-email: Bernát Gábor <gaborjbernat@gmail.com>
11
+ License: Permission is hereby granted, free of charge, to any person obtaining a
12
+ copy of this software and associated documentation files (the
13
+ "Software"), to deal in the Software without restriction, including
14
+ without limitation the rights to use, copy, modify, merge, publish,
15
+ distribute, sublicense, and/or sell copies of the Software, and to
16
+ permit persons to whom the Software is furnished to do so, subject to
17
+ the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included
20
+ in all copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
25
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
26
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
27
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
28
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: discovery,interpreter,python
31
+ Classifier: Development Status :: 5 - Production/Stable
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Operating System :: MacOS :: MacOS X
35
+ Classifier: Operating System :: Microsoft :: Windows
36
+ Classifier: Operating System :: POSIX
37
+ Classifier: Programming Language :: Python :: 3 :: Only
38
+ Classifier: Programming Language :: Python :: 3.8
39
+ Classifier: Programming Language :: Python :: 3.9
40
+ Classifier: Programming Language :: Python :: 3.10
41
+ Classifier: Programming Language :: Python :: 3.11
42
+ Classifier: Programming Language :: Python :: 3.12
43
+ Classifier: Programming Language :: Python :: 3.13
44
+ Classifier: Programming Language :: Python :: 3.14
45
+ Classifier: Programming Language :: Python :: Implementation :: CPython
46
+ Classifier: Topic :: Software Development :: Libraries
47
+ Classifier: Topic :: Utilities
48
+ Requires-Python: >=3.8
49
+ Requires-Dist: filelock>=3.15.4
50
+ Requires-Dist: platformdirs<5,>=4.3.6
51
+ Provides-Extra: docs
52
+ Requires-Dist: furo>=2025.12.19; extra == 'docs'
53
+ Requires-Dist: sphinx-autodoc-typehints>=3.6.3; extra == 'docs'
54
+ Requires-Dist: sphinx>=9.1; extra == 'docs'
55
+ Requires-Dist: sphinxcontrib-mermaid>=2; extra == 'docs'
56
+ Provides-Extra: testing
57
+ Requires-Dist: covdefaults>=2.3; extra == 'testing'
58
+ Requires-Dist: coverage>=7.5.4; extra == 'testing'
59
+ Requires-Dist: pytest-mock>=3.14; extra == 'testing'
60
+ Requires-Dist: pytest>=8.3.5; extra == 'testing'
61
+ Requires-Dist: setuptools>=75.1; extra == 'testing'
62
+ Description-Content-Type: text/markdown
63
+
64
+ # [`python-discovery`](https://python-discovery.readthedocs.io/en/latest/)
65
+
66
+ [![PyPI](https://img.shields.io/pypi/v/python-discovery?style=flat-square)](https://pypi.org/project/python-discovery/)
67
+ [![Supported Python
68
+ versions](https://img.shields.io/pypi/pyversions/python-discovery.svg)](https://pypi.org/project/python-discovery/)
69
+ [![Downloads](https://static.pepy.tech/badge/python-discovery/month)](https://pepy.tech/project/python-discovery)
70
+ [![check](https://github.com/tox-dev/python-discovery/actions/workflows/check.yml/badge.svg)](https://github.com/tox-dev/python-discovery/actions/workflows/check.yml)
71
+ [![Documentation Status](https://readthedocs.org/projects/python-discovery/badge/?version=latest)](https://python-discovery.readthedocs.io/en/latest/?badge=latest)
@@ -0,0 +1,16 @@
1
+ python_discovery/__init__.py,sha256=0uFXdlOPCzMeqnwpyYglvqxs64P_PpidbwIzdWJEroc,483
2
+ python_discovery/_cache.py,sha256=gQT6iqLj0-JF_lVDYsi0n05t9RekM7RWbUb0SfFCN5s,4159
3
+ python_discovery/_cached_py_info.py,sha256=1u90GMe9uSfFh5jFFKMy3M0PXee89217mAjPE2wlJSA,8309
4
+ python_discovery/_compat.py,sha256=iqxGuhK9rPaiui80G1H1KrweoMJ16gyLYEmUrSXrp5c,709
5
+ python_discovery/_discovery.py,sha256=z4nVspl0L0_5NiRVut_us9kbWDtXnkzsLBSM7RaL-mU,11236
6
+ python_discovery/_py_info.py,sha256=T6RJEewEi2aVC6MJOMv2e3Xor4d55M5YUAXY6Idi2sA,30807
7
+ python_discovery/_py_spec.py,sha256=VsHl6k_SwiZlviUk3KcSn9D83_ersKqs8OBiRcztucc,8385
8
+ python_discovery/_specifier.py,sha256=gLaqTrZhp2woUSYHpZayLqfpgTn9914ZM3WPXC8AKMM,8744
9
+ python_discovery/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ python_discovery/_windows/__init__.py,sha256=qthcyGh36b3WkeSbZ4ECRRYLbCOCaQu5X_DRZ98tXfk,315
11
+ python_discovery/_windows/_pep514.py,sha256=JYSQ5tOYbSMOKtVVfOEkyYskBhEoTsImNr3DJcv7XNE,7658
12
+ python_discovery/_windows/_propose.py,sha256=iMJf6l0TU4SvuV8UsCHHINAe9L5dUT949xyeyMVdong,1565
13
+ python_discovery-1.0.0.dist-info/METADATA,sha256=JqrmW6S_Jxb0qUk--KSpfwaYTuiBOEIdGbTdyN87F50,4022
14
+ python_discovery-1.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
15
+ python_discovery-1.0.0.dist-info/licenses/LICENSE,sha256=kOJeH68qSq6o2V7o5_VziwUqGswMnFgGgQH5Mahr1Yg,1023
16
+ python_discovery-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,18 @@
1
+ Permission is hereby granted, free of charge, to any person obtaining a
2
+ copy of this software and associated documentation files (the
3
+ "Software"), to deal in the Software without restriction, including
4
+ without limitation the rights to use, copy, modify, merge, publish,
5
+ distribute, sublicense, and/or sell copies of the Software, and to
6
+ permit persons to whom the Software is furnished to do so, subject to
7
+ the following conditions:
8
+
9
+ The above copyright notice and this permission notice shall be included
10
+ in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
15
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
16
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
17
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
18
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.