Debian Codegraph @

Lib/sysconfig/__init__.py

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 """Access to Python's configuration information."""
2
3 import os
4 import sys
5 import threading
6 from os.path import realpath
7
8 __all__ = [
9 'get_config_h_filename',
10 'get_config_var',
11 'get_config_vars',
12 'get_makefile_filename',
13 'get_path',
14 'get_path_names',
15 'get_paths',
16 'get_platform',
17 'get_python_version',
18 'get_scheme_names',
19 'parse_config_h',
20 ]
21
22 # Keys for get_config_var() that are never converted to Python integers.
23 _ALWAYS_STR = {
24 'IPHONEOS_DEPLOYMENT_TARGET',
25 'MACOSX_DEPLOYMENT_TARGET',
26 }
27
28 _INSTALL_SCHEMES = {
29 'posix_prefix': {
30 'stdlib': '{installed_base}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
31 'platstdlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
32 'purelib': '{base}/lib/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
33 'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
34 'include':
35 '{installed_base}/include/{implementation_lower}{py_version_short}{abiflags}',
36 'platinclude':
37 '{installed_platbase}/include/{implementation_lower}{py_version_short}{abiflags}',
38 'scripts': '{base}/bin',
39 'data': '{base}',
40 },
41 'posix_home': {
42 'stdlib': '{installed_base}/lib/{implementation_lower}',
43 'platstdlib': '{base}/lib/{implementation_lower}',
44 'purelib': '{base}/lib/{implementation_lower}',
45 'platlib': '{base}/lib/{implementation_lower}',
46 'include': '{installed_base}/include/{implementation_lower}',
47 'platinclude': '{installed_base}/include/{implementation_lower}',
48 'scripts': '{base}/bin',
49 'data': '{base}',
50 },
51 'nt': {
52 'stdlib': '{installed_base}/Lib',
53 'platstdlib': '{base}/Lib',
54 'purelib': '{base}/Lib/site-packages',
55 'platlib': '{base}/Lib/site-packages',
56 'include': '{installed_base}/Include',
57 'platinclude': '{installed_base}/Include',
58 'scripts': '{base}/Scripts',
59 'data': '{base}',
60 },
61
62 # Downstream distributors can overwrite the default install scheme.
63 # This is done to support downstream modifications where distributors change
64 # the installation layout (eg. different site-packages directory).
65 # So, distributors will change the default scheme to one that correctly
66 # represents their layout.
67 # This presents an issue for projects/people that need to bootstrap virtual
68 # environments, like virtualenv. As distributors might now be customizing
69 # the default install scheme, there is no guarantee that the information
70 # returned by sysconfig.get_default_scheme/get_paths is correct for
71 # a virtual environment, the only guarantee we have is that it is correct
72 # for the *current* environment. When bootstrapping a virtual environment,
73 # we need to know its layout, so that we can place the files in the
74 # correct locations.
75 # The "*_venv" install scheme is a scheme to bootstrap virtual environments,
76 # essentially identical to the default posix_prefix/nt schemes.
77 # Downstream distributors who patch posix_prefix/nt scheme are encouraged to
78 # leave the following schemes unchanged
79 'posix_venv': {
80 'stdlib': '{installed_base}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
81 'platstdlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
82 'purelib': '{base}/lib/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
83 'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
84 'include':
85 '{installed_base}/include/{implementation_lower}{py_version_short}{abiflags}',
86 'platinclude':
87 '{installed_platbase}/include/{implementation_lower}{py_version_short}{abiflags}',
88 'scripts': '{base}/bin',
89 'data': '{base}',
90 },
91 'nt_venv': {
92 'stdlib': '{installed_base}/Lib',
93 'platstdlib': '{base}/Lib',
94 'purelib': '{base}/Lib/site-packages',
95 'platlib': '{base}/Lib/site-packages',
96 'include': '{installed_base}/Include',
97 'platinclude': '{installed_base}/Include',
98 'scripts': '{base}/Scripts',
99 'data': '{base}',
100 },
101 }
102
103 # For the OS-native venv scheme, we essentially provide an alias:
104 if os.name == 'nt':
105 _INSTALL_SCHEMES['venv'] = _INSTALL_SCHEMES['nt_venv']
106 else:
107 _INSTALL_SCHEMES['venv'] = _INSTALL_SCHEMES['posix_venv']
108
109 def _get_implementation():
110 return 'Python'
111
112 # NOTE: site.py has copy of this function.
113 # Sync it when modify this function.
114 def _getuserbase():
115 env_base = os.environ.get("PYTHONUSERBASE", None)
116 if env_base:
117 return env_base
118
119 # Emscripten, iOS, tvOS, VxWorks, WASI, and watchOS have no home directories
120 if sys.platform in {"emscripten", "ios", "tvos", "vxworks", "wasi", "watchos"}:
121 return None
122
123 def joinuser(*args):
124 return os.path.expanduser(os.path.join(*args))
125
126 if os.name == "nt":
127 base = os.environ.get("APPDATA") or "~"
128 return joinuser(base, _get_implementation())
129
130 if sys.platform == "darwin" and sys._framework:
131 return joinuser("~", "Library", sys._framework,
132 f"{sys.version_info[0]}.{sys.version_info[1]}")
133
134 return joinuser("~", ".local")
135
136 _HAS_USER_BASE = (_getuserbase() is not None)
137
138 if _HAS_USER_BASE:
139 _INSTALL_SCHEMES |= {
140 # NOTE: When modifying "purelib" scheme, update site._get_path() too.
141 'nt_user': {
142 'stdlib': '{userbase}/{implementation}{py_version_nodot_plat}',
143 'platstdlib': '{userbase}/{implementation}{py_version_nodot_plat}',
144 'purelib': '{userbase}/{implementation}{py_version_nodot_plat}/site-packages',
145 'platlib': '{userbase}/{implementation}{py_version_nodot_plat}/site-packages',
146 'include': '{userbase}/{implementation}{py_version_nodot_plat}/Include',
147 'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
148 'data': '{userbase}',
149 },
150 'posix_user': {
151 'stdlib': '{userbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
152 'platstdlib': '{userbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
153 'purelib': '{userbase}/lib/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
154 'platlib': '{userbase}/lib/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
155 'include': '{userbase}/include/{implementation_lower}{py_version_short}{abi_thread}',
156 'scripts': '{userbase}/bin',
157 'data': '{userbase}',
158 },
159 'osx_framework_user': {
160 'stdlib': '{userbase}/lib/{implementation_lower}',
161 'platstdlib': '{userbase}/lib/{implementation_lower}',
162 'purelib': '{userbase}/lib/{implementation_lower}/site-packages',
163 'platlib': '{userbase}/lib/{implementation_lower}/site-packages',
164 'include': '{userbase}/include/{implementation_lower}{py_version_short}',
165 'scripts': '{userbase}/bin',
166 'data': '{userbase}',
167 },
168 }
169
170 _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
171 'scripts', 'data')
172
173 _PY_VERSION = sys.version.split()[0]
174 _PY_VERSION_SHORT = f'{sys.version_info[0]}.{sys.version_info[1]}'
175 _PY_VERSION_SHORT_NO_DOT = f'{sys.version_info[0]}{sys.version_info[1]}'
176 _BASE_PREFIX = os.path.normpath(sys.base_prefix)
177 _BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
178 # Mutex guarding initialization of _CONFIG_VARS.
179 _CONFIG_VARS_LOCK = threading.RLock()
180 _CONFIG_VARS = None
181 # True iff _CONFIG_VARS has been fully initialized.
182 _CONFIG_VARS_INITIALIZED = False
183 _USER_BASE = None
184
185
186 def _safe_realpath(path):
187 try:
188 return realpath(path)
189 except OSError:
190 return path
191
192 if sys.executable:
193 _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
194 else:
195 # sys.executable can be empty if argv[0] has been changed and Python is
196 # unable to retrieve the real program name
197 _PROJECT_BASE = _safe_realpath(os.getcwd())
198
199 # In a virtual environment, `sys._home` gives us the target directory
200 # `_PROJECT_BASE` for the executable that created it when the virtual
201 # python is an actual executable ('venv --copies' or Windows).
202 _sys_home = getattr(sys, '_home', None)
203 if _sys_home:
204 _PROJECT_BASE = _sys_home
205
206 if os.name == 'nt':
207 # In a source build, the executable is in a subdirectory of the root
208 # that we want (<root>\PCbuild\<platname>).
209 # `_BASE_PREFIX` is used as the base installation is where the source
210 # will be. The realpath is needed to prevent mount point confusion
211 # that can occur with just string comparisons.
212 if _safe_realpath(_PROJECT_BASE).startswith(
213 _safe_realpath(f'{_BASE_PREFIX}\\PCbuild')):
214 _PROJECT_BASE = _BASE_PREFIX
215
216 # set for cross builds
217 if "_PYTHON_PROJECT_BASE" in os.environ:
218 _PROJECT_BASE = _safe_realpath(os.environ["_PYTHON_PROJECT_BASE"])
219
220 def is_python_build(check_home=None):
221 if check_home is not None:
222 import warnings
223 warnings.warn(
224 (
225 'The check_home argument of sysconfig.is_python_build is '
226 'deprecated and its value is ignored. '
227 'It will be removed in Python 3.15.'
228 ),
229 DeprecationWarning,
230 stacklevel=2,
231 )
232 for fn in ("Setup", "Setup.local"):
233 if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)):
234 return True
235 return False
236
237 _PYTHON_BUILD = is_python_build()
238
239 if _PYTHON_BUILD:
240 for scheme in ('posix_prefix', 'posix_home'):
241 # On POSIX-y platforms, Python will:
242 # - Build from .h files in 'headers' (which is only added to the
243 # scheme when building CPython)
244 # - Install .h files to 'include'
245 scheme = _INSTALL_SCHEMES[scheme]
246 scheme['headers'] = scheme['include']
247 scheme['include'] = '{srcdir}/Include'
248 scheme['platinclude'] = '{projectbase}/.'
249 del scheme
250
251
252 def _subst_vars(s, local_vars):
253 try:
254 return s.format(**local_vars)
255 except KeyError as var:
256 try:
257 return s.format(**os.environ)
258 except KeyError:
259 raise AttributeError(f'{var}') from None
260
261 def _extend_dict(target_dict, other_dict):
262 target_keys = target_dict.keys()
263 for key, value in other_dict.items():
264 if key in target_keys:
265 continue
266 target_dict[key] = value
267
268
269 def _expand_vars(scheme, vars):
270 res = {}
271 if vars is None:
272 vars = {}
273 _extend_dict(vars, get_config_vars())
274 if os.name == 'nt':
275 # On Windows we want to substitute 'lib' for schemes rather
276 # than the native value (without modifying vars, in case it
277 # was passed in)
278 vars = vars | {'platlibdir': 'lib'}
279
280 for key, value in _INSTALL_SCHEMES[scheme].items():
281 if os.name in ('posix', 'nt'):
282 value = os.path.expanduser(value)
283 res[key] = os.path.normpath(_subst_vars(value, vars))
284 return res
285
286
287 def _get_preferred_schemes():
288 if os.name == 'nt':
289 return {
290 'prefix': 'nt',
291 'home': 'posix_home',
292 'user': 'nt_user',
293 }
294 if sys.platform == 'darwin' and sys._framework:
295 return {
296 'prefix': 'posix_prefix',
297 'home': 'posix_home',
298 'user': 'osx_framework_user',
299 }
300
301 return {
302 'prefix': 'posix_prefix',
303 'home': 'posix_home',
304 'user': 'posix_user',
305 }
306
307
308 def get_preferred_scheme(key):
309 if key == 'prefix' and sys.prefix != sys.base_prefix:
310 return 'venv'
311 scheme = _get_preferred_schemes()[key]
312 if scheme not in _INSTALL_SCHEMES:
313 raise ValueError(
314 f"{key!r} returned {scheme!r}, which is not a valid scheme "
315 f"on this platform"
316 )
317 return scheme
318
319
320 def get_default_scheme():
321 return get_preferred_scheme('prefix')
322
323
324 def get_makefile_filename():
325 """Return the path of the Makefile."""
326 if _PYTHON_BUILD:
327 return os.path.join(_PROJECT_BASE, "Makefile")
328 if hasattr(sys, 'abiflags'):
329 config_dir_name = f'config-{_PY_VERSION_SHORT}{sys.abiflags}'
330 else:
331 config_dir_name = 'config'
332 if hasattr(sys.implementation, '_multiarch'):
333 config_dir_name += f'-{sys.implementation._multiarch}'
334 return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
335
336
337 def _get_sysconfigdata_name():
338 multiarch = getattr(sys.implementation, '_multiarch', '')
339 return os.environ.get(
340 '_PYTHON_SYSCONFIGDATA_NAME',
341 f'_sysconfigdata_{sys.abiflags}_{sys.platform}_{multiarch}',
342 )
343
344 def _init_posix(vars):
345 """Initialize the module as appropriate for POSIX systems."""
346 # _sysconfigdata is generated at build time, see _generate_posix_vars()
347 name = _get_sysconfigdata_name()
348
349 # For cross builds, the path to the target's sysconfigdata must be specified
350 # so it can be imported. It cannot be in PYTHONPATH, as foreign modules in
351 # sys.path can cause crashes when loaded by the host interpreter.
352 # Rely on truthiness as a valueless env variable is still an empty string.
353 # See OS X note in _generate_posix_vars re _sysconfigdata.
354 if (path := os.environ.get('_PYTHON_SYSCONFIGDATA_PATH')):
355 from importlib.machinery import FileFinder, SourceFileLoader, SOURCE_SUFFIXES
356 from importlib.util import module_from_spec
357 spec = FileFinder(path, (SourceFileLoader, SOURCE_SUFFIXES)).find_spec(name)
358 _temp = module_from_spec(spec)
359 spec.loader.exec_module(_temp)
360 else:
361 _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
362 build_time_vars = _temp.build_time_vars
363 vars.update(build_time_vars)
364
365 def _init_non_posix(vars):
366 """Initialize the module as appropriate for NT"""
367 # set basic install directories
368 import _winapi
369 import _sysconfig
370 vars['LIBDEST'] = get_path('stdlib')
371 vars['BINLIBDEST'] = get_path('platstdlib')
372 vars['INCLUDEPY'] = get_path('include')
373
374 # Add EXT_SUFFIX, SOABI, and Py_GIL_DISABLED
375 vars.update(_sysconfig.config_vars())
376
377 vars['LIBDIR'] = _safe_realpath(os.path.join(get_config_var('installed_base'), 'libs'))
378 if hasattr(sys, 'dllhandle'):
379 dllhandle = _winapi.GetModuleFileName(sys.dllhandle)
380 vars['LIBRARY'] = os.path.basename(_safe_realpath(dllhandle))
381 vars['LDLIBRARY'] = vars['LIBRARY']
382 vars['EXE'] = '.exe'
383 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
384 vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
385 vars['TZPATH'] = ''
386
387 #
388 # public APIs
389 #
390
391
392 def parse_config_h(fp, vars=None):
393 """Parse a config.h-style file.
394
395 A dictionary containing name/value pairs is returned. If an
396 optional dictionary is passed in as the second argument, it is
397 used instead of a new dictionary.
398 """
399 if vars is None:
400 vars = {}
401 import re
402 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
403 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
404
405 while True:
406 line = fp.readline()
407 if not line:
408 break
409 m = define_rx.match(line)
410 if m:
411 n, v = m.group(1, 2)
412 try:
413 if n in _ALWAYS_STR:
414 raise ValueError
415 v = int(v)
416 except ValueError:
417 pass
418 vars[n] = v
419 else:
420 m = undef_rx.match(line)
421 if m:
422 vars[m.group(1)] = 0
423 return vars
424
425
426 def get_config_h_filename():
427 """Return the path of pyconfig.h."""
428 if _PYTHON_BUILD:
429 if os.name == "nt":
430 inc_dir = os.path.dirname(sys._base_executable)
431 else:
432 inc_dir = _PROJECT_BASE
433 else:
434 inc_dir = get_path('platinclude')
435 return os.path.join(inc_dir, 'pyconfig.h')
436
437
438 def get_scheme_names():
439 """Return a tuple containing the schemes names."""
440 return tuple(sorted(_INSTALL_SCHEMES))
441
442
443 def get_path_names():
444 """Return a tuple containing the paths names."""
445 return _SCHEME_KEYS
446
447
448 def get_paths(scheme=get_default_scheme(), vars=None, expand=True):
449 """Return a mapping containing an install scheme.
450
451 ``scheme`` is the install scheme name. If not provided, it will
452 return the default scheme for the current platform.
453 """
454 if expand:
455 return _expand_vars(scheme, vars)
456 else:
457 return _INSTALL_SCHEMES[scheme]
458
459
460 def get_path(name, scheme=get_default_scheme(), vars=None, expand=True):
461 """Return a path corresponding to the scheme.
462
463 ``scheme`` is the install scheme name.
464 """
465 return get_paths(scheme, vars, expand)[name]
466
467
468 def _init_config_vars():
469 global _CONFIG_VARS
470 _CONFIG_VARS = {}
471 # Normalized versions of prefix and exec_prefix are handy to have;
472 # in fact, these are the standard versions used most places in the
473 # Distutils.
474 _PREFIX = os.path.normpath(sys.prefix)
475 _EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
476 _CONFIG_VARS['prefix'] = _PREFIX # FIXME: This gets overwriten by _init_posix.
477 _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX # FIXME: This gets overwriten by _init_posix.
478 _CONFIG_VARS['py_version'] = _PY_VERSION
479 _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
480 _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT
481 _CONFIG_VARS['installed_base'] = _BASE_PREFIX
482 _CONFIG_VARS['base'] = _PREFIX
483 _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX
484 _CONFIG_VARS['platbase'] = _EXEC_PREFIX
485 _CONFIG_VARS['projectbase'] = _PROJECT_BASE
486 _CONFIG_VARS['platlibdir'] = sys.platlibdir
487 _CONFIG_VARS['implementation'] = _get_implementation()
488 _CONFIG_VARS['implementation_lower'] = _get_implementation().lower()
489 try:
490 _CONFIG_VARS['abiflags'] = sys.abiflags
491 except AttributeError:
492 # sys.abiflags may not be defined on all platforms.
493 _CONFIG_VARS['abiflags'] = ''
494 try:
495 _CONFIG_VARS['py_version_nodot_plat'] = sys.winver.replace('.', '')
496 except AttributeError:
497 _CONFIG_VARS['py_version_nodot_plat'] = ''
498
499 if os.name == 'nt':
500 _init_non_posix(_CONFIG_VARS)
501 _CONFIG_VARS['VPATH'] = sys._vpath
502 if os.name == 'posix':
503 _init_posix(_CONFIG_VARS)
504 if _HAS_USER_BASE:
505 # Setting 'userbase' is done below the call to the
506 # init function to enable using 'get_config_var' in
507 # the init-function.
508 _CONFIG_VARS['userbase'] = _getuserbase()
509
510 # e.g., 't' for free-threaded or '' for default build
511 _CONFIG_VARS['abi_thread'] = 't' if _CONFIG_VARS.get('Py_GIL_DISABLED') else ''
512
513 # Always convert srcdir to an absolute path
514 srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
515 if os.name == 'posix':
516 if _PYTHON_BUILD:
517 # If srcdir is a relative path (typically '.' or '..')
518 # then it should be interpreted relative to the directory
519 # containing Makefile.
520 base = os.path.dirname(get_makefile_filename())
521 srcdir = os.path.join(base, srcdir)
522 else:
523 # srcdir is not meaningful since the installation is
524 # spread about the filesystem. We choose the
525 # directory containing the Makefile since we know it
526 # exists.
527 srcdir = os.path.dirname(get_makefile_filename())
528 _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
529
530 # OS X platforms require special customization to handle
531 # multi-architecture, multi-os-version installers
532 if sys.platform == 'darwin':
533 import _osx_support
534 _osx_support.customize_config_vars(_CONFIG_VARS)
535
536 global _CONFIG_VARS_INITIALIZED
537 _CONFIG_VARS_INITIALIZED = True
538
539
540 def get_config_vars(*args):
541 """With no arguments, return a dictionary of all configuration
542 variables relevant for the current platform.
543
544 On Unix, this means every variable defined in Python's installed Makefile;
545 On Windows it's a much smaller set.
546
547 With arguments, return a list of values that result from looking up
548 each argument in the configuration variable dictionary.
549 """
550 global _CONFIG_VARS_INITIALIZED
551
552 # Avoid claiming the lock once initialization is complete.
553 if not _CONFIG_VARS_INITIALIZED:
554 with _CONFIG_VARS_LOCK:
555 # Test again with the lock held to avoid races. Note that
556 # we test _CONFIG_VARS here, not _CONFIG_VARS_INITIALIZED,
557 # to ensure that recursive calls to get_config_vars()
558 # don't re-enter init_config_vars().
559 if _CONFIG_VARS is None:
560 _init_config_vars()
561 else:
562 # If the site module initialization happened after _CONFIG_VARS was
563 # initialized, a virtual environment might have been activated, resulting in
564 # variables like sys.prefix changing their value, so we need to re-init the
565 # config vars (see GH-126789).
566 if _CONFIG_VARS['base'] != os.path.normpath(sys.prefix):
567 with _CONFIG_VARS_LOCK:
568 _CONFIG_VARS_INITIALIZED = False
569 _init_config_vars()
570
571 if args:
572 vals = []
573 for name in args:
574 vals.append(_CONFIG_VARS.get(name))
575 return vals
576 else:
577 return _CONFIG_VARS
578
579
580 def get_config_var(name):
581 """Return the value of a single variable using the dictionary returned by
582 'get_config_vars()'.
583
584 Equivalent to get_config_vars().get(name)
585 """
586 return get_config_vars().get(name)
587
588
589 def get_platform():
590 """Return a string that identifies the current platform.
591
592 This is used mainly to distinguish platform-specific build directories and
593 platform-specific built distributions. Typically includes the OS name and
594 version and the architecture (as supplied by 'os.uname()'), although the
595 exact information included depends on the OS; on Linux, the kernel version
596 isn't particularly important.
597
598 Examples of returned values:
599
600
601 Windows:
602
603 - win-amd64 (64-bit Windows on AMD64, aka x86_64, Intel64, and EM64T)
604 - win-arm64 (64-bit Windows on ARM64, aka AArch64)
605 - win32 (all others - specifically, sys.platform is returned)
606
607 POSIX based OS:
608
609 - linux-x86_64
610 - macosx-15.5-arm64
611 - macosx-26.0-universal2 (macOS on Apple Silicon or Intel)
612 - android-24-arm64_v8a
613
614 For other non-POSIX platforms, currently just returns :data:`sys.platform`."""
615 if os.name == 'nt':
616 if 'amd64' in sys.version.lower():
617 return 'win-amd64'
618 if '(arm)' in sys.version.lower():
619 return 'win-arm32'
620 if '(arm64)' in sys.version.lower():
621 return 'win-arm64'
622 return sys.platform
623
624 if os.name != "posix" or not hasattr(os, 'uname'):
625 # XXX what about the architecture? NT is Intel or Alpha
626 return sys.platform
627
628 # Set for cross builds explicitly
629 if "_PYTHON_HOST_PLATFORM" in os.environ:
630 return os.environ["_PYTHON_HOST_PLATFORM"]
631
632 # Try to distinguish various flavours of Unix
633 osname, host, release, version, machine = os.uname()
634
635 # Convert the OS name to lowercase, remove '/' characters, and translate
636 # spaces (for "Power Macintosh")
637 osname = osname.lower().replace('/', '')
638 machine = machine.replace(' ', '_')
639 machine = machine.replace('/', '-')
640
641 if osname[:5] == "linux":
642 if sys.platform == "android":
643 osname = "android"
644 release = get_config_var("ANDROID_API_LEVEL")
645
646 # Wheel tags use the ABI names from Android's own tools.
647 machine = {
648 "x86_64": "x86_64",
649 "i686": "x86",
650 "aarch64": "arm64_v8a",
651 "armv7l": "armeabi_v7a",
652 }[machine]
653 else:
654 # At least on Linux/Intel, 'machine' is the processor --
655 # i386, etc.
656 # XXX what about Alpha, SPARC, etc?
657 return f"{osname}-{machine}"
658 elif osname[:5] == "sunos":
659 if release[0] >= "5": # SunOS 5 == Solaris 2
660 osname = "solaris"
661 release = f"{int(release[0]) - 3}.{release[2:]}"
662 # We can't use "platform.architecture()[0]" because a
663 # bootstrap problem. We use a dict to get an error
664 # if some suspicious happens.
665 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
666 machine += f".{bitness[sys.maxsize]}"
667 # fall through to standard osname-release-machine representation
668 elif osname[:3] == "aix":
669 from _aix_support import aix_platform
670 return aix_platform()
671 elif osname[:6] == "cygwin":
672 osname = "cygwin"
673 import re
674 rel_re = re.compile(r'[\d.]+')
675 m = rel_re.match(release)
676 if m:
677 release = m.group()
678 elif osname[:6] == "darwin":
679 if sys.platform == "ios":
680 release = get_config_vars().get("IPHONEOS_DEPLOYMENT_TARGET", "13.0")
681 osname = sys.platform
682 machine = sys.implementation._multiarch
683 else:
684 import _osx_support
685 osname, release, machine = _osx_support.get_platform_osx(
686 get_config_vars(),
687 osname, release, machine)
688
689 return f"{osname}-{release}-{machine}"
690
691
692 def get_python_version():
693 return _PY_VERSION_SHORT
694
695
696 def _get_python_version_abi():
697 return _PY_VERSION_SHORT + get_config_var("abi_thread")
698
699
700 def expand_makefile_vars(s, vars):
701 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
702 'string' according to 'vars' (a dictionary mapping variable names to
703 values). Variables not present in 'vars' are silently expanded to the
704 empty string. The variable values in 'vars' should not contain further
705 variable expansions; if 'vars' is the output of 'parse_makefile()',
706 you're fine. Returns a variable-expanded version of 's'.
707 """
708 import re
709
710 _findvar1_rx = r"\$\(([A-Za-z][A-Za-z0-9_]*)\)"
711 _findvar2_rx = r"\${([A-Za-z][A-Za-z0-9_]*)}"
712
713 # This algorithm does multiple expansion, so if vars['foo'] contains
714 # "${bar}", it will expand ${foo} to ${bar}, and then expand
715 # ${bar}... and so forth. This is fine as long as 'vars' comes from
716 # 'parse_makefile()', which takes care of such expansions eagerly,
717 # according to make's variable expansion semantics.
718
719 while True:
720 m = re.search(_findvar1_rx, s) or re.search(_findvar2_rx, s)
721 if m:
722 (beg, end) = m.span()
723 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
724 else:
725 break
726 return s