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 # Use _PYTHON_HOST_PLATFORM to get the correct platform when cross-compiling.
121 system_name = os.environ.get('_PYTHON_HOST_PLATFORM', sys.platform).split('-')[0]
122 if system_name in {"emscripten", "ios", "tvos", "vxworks", "wasi", "watchos"}:
123 return None
124
125 def joinuser(*args):
126 return os.path.expanduser(os.path.join(*args))
127
128 if os.name == "nt":
129 base = os.environ.get("APPDATA") or "~"
130 return joinuser(base, _get_implementation())
131
132 if sys.platform == "darwin" and sys._framework:
133 return joinuser("~", "Library", sys._framework,
134 f"{sys.version_info[0]}.{sys.version_info[1]}")
135
136 return joinuser("~", ".local")
137
138 _HAS_USER_BASE = (_getuserbase() is not None)
139
140 if _HAS_USER_BASE:
141 _INSTALL_SCHEMES |= {
142 # NOTE: When modifying "purelib" scheme, update site._get_path() too.
143 'nt_user': {
144 'stdlib': '{userbase}/{implementation}{py_version_nodot_plat}',
145 'platstdlib': '{userbase}/{implementation}{py_version_nodot_plat}',
146 'purelib': '{userbase}/{implementation}{py_version_nodot_plat}/site-packages',
147 'platlib': '{userbase}/{implementation}{py_version_nodot_plat}/site-packages',
148 'include': '{userbase}/{implementation}{py_version_nodot_plat}/Include',
149 'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
150 'data': '{userbase}',
151 },
152 'posix_user': {
153 'stdlib': '{userbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
154 'platstdlib': '{userbase}/{platlibdir}/{implementation_lower}{py_version_short}{abi_thread}',
155 'purelib': '{userbase}/lib/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
156 'platlib': '{userbase}/lib/{implementation_lower}{py_version_short}{abi_thread}/site-packages',
157 'include': '{userbase}/include/{implementation_lower}{py_version_short}{abi_thread}',
158 'scripts': '{userbase}/bin',
159 'data': '{userbase}',
160 },
161 'osx_framework_user': {
162 'stdlib': '{userbase}/lib/{implementation_lower}',
163 'platstdlib': '{userbase}/lib/{implementation_lower}',
164 'purelib': '{userbase}/lib/{implementation_lower}/site-packages',
165 'platlib': '{userbase}/lib/{implementation_lower}/site-packages',
166 'include': '{userbase}/include/{implementation_lower}{py_version_short}',
167 'scripts': '{userbase}/bin',
168 'data': '{userbase}',
169 },
170 }
171
172 _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
173 'scripts', 'data')
174
175 _PY_VERSION = sys.version.split()[0]
176 _PY_VERSION_SHORT = f'{sys.version_info[0]}.{sys.version_info[1]}'
177 _PY_VERSION_SHORT_NO_DOT = f'{sys.version_info[0]}{sys.version_info[1]}'
178 _BASE_PREFIX = os.path.normpath(sys.base_prefix)
179 _BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
180 # Mutex guarding initialization of _CONFIG_VARS.
181 _CONFIG_VARS_LOCK = threading.RLock()
182 _CONFIG_VARS = None
183 # True iff _CONFIG_VARS has been fully initialized.
184 _CONFIG_VARS_INITIALIZED = False
185 _USER_BASE = None
186
187
188 def _safe_realpath(path):
189 try:
190 return realpath(path)
191 except OSError:
192 return path
193
194 if sys.executable:
195 _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
196 else:
197 # sys.executable can be empty if argv[0] has been changed and Python is
198 # unable to retrieve the real program name
199 _PROJECT_BASE = _safe_realpath(os.getcwd())
200
201 # In a virtual environment, `sys._home` gives us the target directory
202 # `_PROJECT_BASE` for the executable that created it when the virtual
203 # python is an actual executable ('venv --copies' or Windows).
204 _sys_home = getattr(sys, '_home', None)
205 if _sys_home:
206 _PROJECT_BASE = _sys_home
207
208 if os.name == 'nt':
209 # In a source build, the executable is in a subdirectory of the root
210 # that we want (<root>\PCbuild\<platname>).
211 # `_BASE_PREFIX` is used as the base installation is where the source
212 # will be. The realpath is needed to prevent mount point confusion
213 # that can occur with just string comparisons.
214 if _safe_realpath(_PROJECT_BASE).startswith(
215 _safe_realpath(f'{_BASE_PREFIX}\\PCbuild')):
216 _PROJECT_BASE = _BASE_PREFIX
217
218 # set for cross builds
219 if "_PYTHON_PROJECT_BASE" in os.environ:
220 _PROJECT_BASE = _safe_realpath(os.environ["_PYTHON_PROJECT_BASE"])
221
222 def is_python_build(check_home=None):
223 if check_home is not None:
224 import warnings
225 warnings.warn(
226 (
227 'The check_home argument of sysconfig.is_python_build is '
228 'deprecated and its value is ignored. '
229 'It will be removed in Python 3.15.'
230 ),
231 DeprecationWarning,
232 stacklevel=2,
233 )
234 for fn in ("Setup", "Setup.local"):
235 if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)):
236 return True
237 return False
238
239 _PYTHON_BUILD = is_python_build()
240
241 if _PYTHON_BUILD:
242 for scheme in ('posix_prefix', 'posix_home'):
243 # On POSIX-y platforms, Python will:
244 # - Build from .h files in 'headers' (which is only added to the
245 # scheme when building CPython)
246 # - Install .h files to 'include'
247 scheme = _INSTALL_SCHEMES[scheme]
248 scheme['headers'] = scheme['include']
249 scheme['include'] = '{srcdir}/Include'
250 scheme['platinclude'] = '{projectbase}/.'
251 del scheme
252
253
254 def _subst_vars(s, local_vars):
255 try:
256 return s.format(**local_vars)
257 except KeyError as var:
258 try:
259 return s.format(**os.environ)
260 except KeyError:
261 raise AttributeError(f'{var}') from None
262
263 def _extend_dict(target_dict, other_dict):
264 target_keys = target_dict.keys()
265 for key, value in other_dict.items():
266 if key in target_keys:
267 continue
268 target_dict[key] = value
269
270
271 def _expand_vars(scheme, vars):
272 res = {}
273 if vars is None:
274 vars = {}
275 _extend_dict(vars, get_config_vars())
276 if os.name == 'nt':
277 # On Windows we want to substitute 'lib' for schemes rather
278 # than the native value (without modifying vars, in case it
279 # was passed in)
280 vars = vars | {'platlibdir': 'lib'}
281
282 for key, value in _INSTALL_SCHEMES[scheme].items():
283 if os.name in ('posix', 'nt'):
284 value = os.path.expanduser(value)
285 res[key] = os.path.normpath(_subst_vars(value, vars))
286 return res
287
288
289 def _get_preferred_schemes():
290 if os.name == 'nt':
291 return {
292 'prefix': 'nt',
293 'home': 'posix_home',
294 'user': 'nt_user',
295 }
296 if sys.platform == 'darwin' and sys._framework:
297 return {
298 'prefix': 'posix_prefix',
299 'home': 'posix_home',
300 'user': 'osx_framework_user',
301 }
302
303 return {
304 'prefix': 'posix_prefix',
305 'home': 'posix_home',
306 'user': 'posix_user',
307 }
308
309
310 def get_preferred_scheme(key):
311 if key == 'prefix' and sys.prefix != sys.base_prefix:
312 return 'venv'
313 scheme = _get_preferred_schemes()[key]
314 if scheme not in _INSTALL_SCHEMES:
315 raise ValueError(
316 f"{key!r} returned {scheme!r}, which is not a valid scheme "
317 f"on this platform"
318 )
319 return scheme
320
321
322 def get_default_scheme():
323 return get_preferred_scheme('prefix')
324
325
326 def get_makefile_filename():
327 """Return the path of the Makefile."""
328
329 # GH-127429: When cross-compiling, use the Makefile from the target, instead of the host Python.
330 if cross_base := os.environ.get('_PYTHON_PROJECT_BASE'):
331 return os.path.join(cross_base, 'Makefile')
332
333 if _PYTHON_BUILD:
334 return os.path.join(_PROJECT_BASE, "Makefile")
335
336 if hasattr(sys, 'abiflags'):
337 config_dir_name = f'config-{_PY_VERSION_SHORT}{sys.abiflags}'
338 else:
339 config_dir_name = 'config'
340
341 if hasattr(sys.implementation, '_multiarch'):
342 config_dir_name += f'-{sys.implementation._multiarch}'
343
344 return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
345
346
347 def _import_from_directory(path, name):
348 if name not in sys.modules:
349 import importlib.machinery
350 import importlib.util
351
352 spec = importlib.machinery.PathFinder.find_spec(name, [path])
353 module = importlib.util.module_from_spec(spec)
354 spec.loader.exec_module(module)
355 sys.modules[name] = module
356 return sys.modules[name]
357
358
359 def _get_sysconfigdata_name():
360 multiarch = getattr(sys.implementation, '_multiarch', '')
361 return os.environ.get(
362 '_PYTHON_SYSCONFIGDATA_NAME',
363 f'_sysconfigdata_{sys.abiflags}_{sys.platform}_{multiarch}',
364 )
365
366
367 def _get_sysconfigdata():
368 import importlib
369
370 name = _get_sysconfigdata_name()
371 path = os.environ.get('_PYTHON_SYSCONFIGDATA_PATH')
372 module = _import_from_directory(path, name) if path else importlib.import_module(name)
373
374 return module.build_time_vars
375
376
377 def _installation_is_relocated():
378 """Is the Python installation running from a different prefix than what was targetted when building?"""
379 if os.name != 'posix':
380 raise NotImplementedError('sysconfig._installation_is_relocated() is currently only supported on POSIX')
381
382 data = _get_sysconfigdata()
383 return (
384 data['prefix'] != getattr(sys, 'base_prefix', '')
385 or data['exec_prefix'] != getattr(sys, 'base_exec_prefix', '')
386 )
387
388
389 def _init_posix(vars):
390 """Initialize the module as appropriate for POSIX systems."""
391 # GH-126920: Make sure we don't overwrite any of the keys already set
392 vars.update(_get_sysconfigdata() | vars)
393
394
395 def _init_non_posix(vars):
396 """Initialize the module as appropriate for NT"""
397 # set basic install directories
398 import _winapi
399 import _sysconfig
400 vars['LIBDEST'] = get_path('stdlib')
401 vars['BINLIBDEST'] = get_path('platstdlib')
402 vars['INCLUDEPY'] = get_path('include')
403
404 # Add EXT_SUFFIX, SOABI, Py_DEBUG, and Py_GIL_DISABLED
405 vars.update(_sysconfig.config_vars())
406
407 # NOTE: ABIFLAGS is only an emulated value. It is not present during build
408 # on Windows. sys.abiflags is absent on Windows and vars['abiflags']
409 # is already widely used to calculate paths, so it should remain an
410 # empty string.
411 vars['ABIFLAGS'] = ''.join(
412 (
413 't' if vars['Py_GIL_DISABLED'] else '',
414 '_d' if vars['Py_DEBUG'] else '',
415 ),
416 )
417
418 vars['LIBDIR'] = _safe_realpath(os.path.join(get_config_var('installed_base'), 'libs'))
419 if hasattr(sys, 'dllhandle'):
420 dllhandle = _winapi.GetModuleFileName(sys.dllhandle)
421 vars['LIBRARY'] = os.path.basename(_safe_realpath(dllhandle))
422 vars['LDLIBRARY'] = vars['LIBRARY']
423 vars['EXE'] = '.exe'
424 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
425 vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
426 vars['TZPATH'] = ''
427
428 #
429 # public APIs
430 #
431
432
433 def parse_config_h(fp, vars=None):
434 """Parse a config.h-style file.
435
436 A dictionary containing name/value pairs is returned. If an
437 optional dictionary is passed in as the second argument, it is
438 used instead of a new dictionary.
439 """
440 if vars is None:
441 vars = {}
442 import re
443 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
444 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
445
446 while True:
447 line = fp.readline()
448 if not line:
449 break
450 m = define_rx.match(line)
451 if m:
452 n, v = m.group(1, 2)
453 try:
454 if n in _ALWAYS_STR:
455 raise ValueError
456 v = int(v)
457 except ValueError:
458 pass
459 vars[n] = v
460 else:
461 m = undef_rx.match(line)
462 if m:
463 vars[m.group(1)] = 0
464 return vars
465
466
467 def get_config_h_filename():
468 """Return the path of pyconfig.h."""
469 if _PYTHON_BUILD:
470 if os.name == "nt":
471 inc_dir = os.path.join(_PROJECT_BASE, 'PC')
472 else:
473 inc_dir = _PROJECT_BASE
474 else:
475 inc_dir = get_path('platinclude')
476 return os.path.join(inc_dir, 'pyconfig.h')
477
478
479 def get_scheme_names():
480 """Return a tuple containing the schemes names."""
481 return tuple(sorted(_INSTALL_SCHEMES))
482
483
484 def get_path_names():
485 """Return a tuple containing the paths names."""
486 return _SCHEME_KEYS
487
488
489 def get_paths(scheme=get_default_scheme(), vars=None, expand=True):
490 """Return a mapping containing an install scheme.
491
492 ``scheme`` is the install scheme name. If not provided, it will
493 return the default scheme for the current platform.
494 """
495 if expand:
496 return _expand_vars(scheme, vars)
497 else:
498 return _INSTALL_SCHEMES[scheme]
499
500
501 def get_path(name, scheme=get_default_scheme(), vars=None, expand=True):
502 """Return a path corresponding to the scheme.
503
504 ``scheme`` is the install scheme name.
505 """
506 return get_paths(scheme, vars, expand)[name]
507
508
509 def _init_config_vars():
510 global _CONFIG_VARS
511 _CONFIG_VARS = {}
512
513 prefix = os.path.normpath(sys.prefix)
514 exec_prefix = os.path.normpath(sys.exec_prefix)
515 base_prefix = _BASE_PREFIX
516 base_exec_prefix = _BASE_EXEC_PREFIX
517
518 try:
519 abiflags = sys.abiflags
520 except AttributeError:
521 abiflags = ''
522
523 if os.name == 'posix':
524 _init_posix(_CONFIG_VARS)
525 # If we are cross-compiling, load the prefixes from the Makefile instead.
526 if '_PYTHON_PROJECT_BASE' in os.environ:
527 prefix = _CONFIG_VARS['host_prefix']
528 exec_prefix = _CONFIG_VARS['host_exec_prefix']
529 base_prefix = _CONFIG_VARS['host_prefix']
530 base_exec_prefix = _CONFIG_VARS['host_exec_prefix']
531 abiflags = _CONFIG_VARS['ABIFLAGS']
532
533 # Normalized versions of prefix and exec_prefix are handy to have;
534 # in fact, these are the standard versions used most places in the
535 # Distutils.
536 _CONFIG_VARS['prefix'] = prefix
537 _CONFIG_VARS['exec_prefix'] = exec_prefix
538 _CONFIG_VARS['py_version'] = _PY_VERSION
539 _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
540 _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT
541 _CONFIG_VARS['installed_base'] = base_prefix
542 _CONFIG_VARS['base'] = prefix
543 _CONFIG_VARS['installed_platbase'] = base_exec_prefix
544 _CONFIG_VARS['platbase'] = exec_prefix
545 _CONFIG_VARS['projectbase'] = _PROJECT_BASE
546 _CONFIG_VARS['platlibdir'] = sys.platlibdir
547 _CONFIG_VARS['implementation'] = _get_implementation()
548 _CONFIG_VARS['implementation_lower'] = _get_implementation().lower()
549 _CONFIG_VARS['abiflags'] = abiflags
550 try:
551 _CONFIG_VARS['py_version_nodot_plat'] = sys.winver.replace('.', '')
552 except AttributeError:
553 _CONFIG_VARS['py_version_nodot_plat'] = ''
554
555 if os.name == 'nt':
556 _init_non_posix(_CONFIG_VARS)
557 _CONFIG_VARS['VPATH'] = sys._vpath
558 if _HAS_USER_BASE:
559 # Setting 'userbase' is done below the call to the
560 # init function to enable using 'get_config_var' in
561 # the init-function.
562 _CONFIG_VARS['userbase'] = _getuserbase()
563
564 # e.g., 't' for free-threaded or '' for default build
565 _CONFIG_VARS['abi_thread'] = 't' if _CONFIG_VARS.get('Py_GIL_DISABLED') else ''
566
567 # Always convert srcdir to an absolute path
568 srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
569 if os.name == 'posix':
570 if _PYTHON_BUILD:
571 # If srcdir is a relative path (typically '.' or '..')
572 # then it should be interpreted relative to the directory
573 # containing Makefile.
574 base = os.path.dirname(get_makefile_filename())
575 srcdir = os.path.join(base, srcdir)
576 else:
577 # srcdir is not meaningful since the installation is
578 # spread about the filesystem. We choose the
579 # directory containing the Makefile since we know it
580 # exists.
581 srcdir = os.path.dirname(get_makefile_filename())
582 _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
583
584 # OS X platforms require special customization to handle
585 # multi-architecture, multi-os-version installers
586 if sys.platform == 'darwin':
587 import _osx_support
588 _osx_support.customize_config_vars(_CONFIG_VARS)
589
590 global _CONFIG_VARS_INITIALIZED
591 _CONFIG_VARS_INITIALIZED = True
592
593
594 def get_config_vars(*args):
595 """With no arguments, return a dictionary of all configuration
596 variables relevant for the current platform.
597
598 On Unix, this means every variable defined in Python's installed Makefile;
599 On Windows it's a much smaller set.
600
601 With arguments, return a list of values that result from looking up
602 each argument in the configuration variable dictionary.
603 """
604 global _CONFIG_VARS_INITIALIZED
605
606 # Avoid claiming the lock once initialization is complete.
607 if _CONFIG_VARS_INITIALIZED:
608 # GH-126789: If sys.prefix or sys.exec_prefix were updated, invalidate the cache.
609 prefix = os.path.normpath(sys.prefix)
610 exec_prefix = os.path.normpath(sys.exec_prefix)
611 if _CONFIG_VARS['prefix'] != prefix or _CONFIG_VARS['exec_prefix'] != exec_prefix:
612 with _CONFIG_VARS_LOCK:
613 _CONFIG_VARS_INITIALIZED = False
614 _init_config_vars()
615 else:
616 # Initialize the config_vars cache.
617 with _CONFIG_VARS_LOCK:
618 # Test again with the lock held to avoid races. Note that
619 # we test _CONFIG_VARS here, not _CONFIG_VARS_INITIALIZED,
620 # to ensure that recursive calls to get_config_vars()
621 # don't re-enter init_config_vars().
622 if _CONFIG_VARS is None:
623 _init_config_vars()
624
625 if args:
626 vals = []
627 for name in args:
628 vals.append(_CONFIG_VARS.get(name))
629 return vals
630 else:
631 return _CONFIG_VARS
632
633
634 def get_config_var(name):
635 """Return the value of a single variable using the dictionary returned by
636 'get_config_vars()'.
637
638 Equivalent to get_config_vars().get(name)
639 """
640 return get_config_vars().get(name)
641
642
643 def get_platform():
644 """Return a string that identifies the current platform.
645
646 This is used mainly to distinguish platform-specific build directories and
647 platform-specific built distributions. Typically includes the OS name and
648 version and the architecture (as supplied by 'os.uname()'), although the
649 exact information included depends on the OS; on Linux, the kernel version
650 isn't particularly important.
651
652 Examples of returned values:
653
654
655 Windows:
656
657 - win-amd64 (64-bit Windows on AMD64, aka x86_64, Intel64, and EM64T)
658 - win-arm64 (64-bit Windows on ARM64, aka AArch64)
659 - win32 (all others - specifically, sys.platform is returned)
660
661 POSIX based OS:
662
663 - linux-x86_64
664 - macosx-15.5-arm64
665 - macosx-26.0-universal2 (macOS on Apple Silicon or Intel)
666 - android-24-arm64_v8a
667
668 For other non-POSIX platforms, currently just returns :data:`sys.platform`."""
669 if os.name == 'nt':
670 if 'amd64' in sys.version.lower():
671 return 'win-amd64'
672 if '(arm)' in sys.version.lower():
673 return 'win-arm32'
674 if '(arm64)' in sys.version.lower():
675 return 'win-arm64'
676 return sys.platform
677
678 if os.name != "posix" or not hasattr(os, 'uname'):
679 # XXX what about the architecture? NT is Intel or Alpha
680 return sys.platform
681
682 # Set for cross builds explicitly
683 if "_PYTHON_HOST_PLATFORM" in os.environ:
684 osname, _, machine = os.environ["_PYTHON_HOST_PLATFORM"].partition('-')
685 release = None
686 else:
687 # Try to distinguish various flavours of Unix
688 osname, host, release, version, machine = os.uname()
689
690 # Convert the OS name to lowercase, remove '/' characters, and translate
691 # spaces (for "Power Macintosh")
692 osname = osname.lower().replace('/', '')
693 machine = machine.replace(' ', '_')
694 machine = machine.replace('/', '-')
695
696 if osname == "android" or sys.platform == "android":
697 osname = "android"
698 release = get_config_var("ANDROID_API_LEVEL")
699
700 # Wheel tags use the ABI names from Android's own tools.
701 # When Python is running on 32-bit ARM Android on a 64-bit ARM kernel,
702 # 'os.uname().machine' is 'armv8l'. Such devices run the same userspace
703 # code as 'armv7l' devices.
704 # During the build process of the Android testbed when targeting 32-bit ARM,
705 # '_PYTHON_HOST_PLATFORM' is 'arm-linux-androideabi', so 'machine' becomes
706 # 'arm'.
707 machine = {
708 "aarch64": "arm64_v8a",
709 "arm": "armeabi_v7a",
710 "armv7l": "armeabi_v7a",
711 "armv8l": "armeabi_v7a",
712 "i686": "x86",
713 "x86_64": "x86_64",
714 }[machine]
715 elif osname == "linux":
716 # At least on Linux/Intel, 'machine' is the processor --
717 # i386, etc.
718 # XXX what about Alpha, SPARC, etc?
719 return f"{osname}-{machine}"
720 elif osname[:5] == "sunos":
721 if release[0] >= "5": # SunOS 5 == Solaris 2
722 osname = "solaris"
723 release = f"{int(release[0]) - 3}.{release[2:]}"
724 # We can't use "platform.architecture()[0]" because a
725 # bootstrap problem. We use a dict to get an error
726 # if some suspicious happens.
727 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
728 machine += f".{bitness[sys.maxsize]}"
729 # fall through to standard osname-release-machine representation
730 elif osname[:3] == "aix":
731 from _aix_support import aix_platform
732 return aix_platform()
733 elif osname[:6] == "cygwin":
734 osname = "cygwin"
735 import re
736 rel_re = re.compile(r'[\d.]+')
737 m = rel_re.match(release)
738 if m:
739 release = m.group()
740 elif osname[:6] == "darwin":
741 if sys.platform == "ios":
742 release = get_config_vars().get("IPHONEOS_DEPLOYMENT_TARGET", "13.0")
743 osname = sys.platform
744 machine = sys.implementation._multiarch
745 else:
746 import _osx_support
747 osname, release, machine = _osx_support.get_platform_osx(
748 get_config_vars(),
749 osname, release, machine)
750
751 return '-'.join(map(str, filter(None, (osname, release, machine))))
752
753
754 def get_python_version():
755 return _PY_VERSION_SHORT
756
757
758 def _get_python_version_abi():
759 return _PY_VERSION_SHORT + get_config_var("abi_thread")
760
761
762 def expand_makefile_vars(s, vars):
763 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
764 'string' according to 'vars' (a dictionary mapping variable names to
765 values). Variables not present in 'vars' are silently expanded to the
766 empty string. The variable values in 'vars' should not contain further
767 variable expansions; if 'vars' is the output of 'parse_makefile()',
768 you're fine. Returns a variable-expanded version of 's'.
769 """
770
771 import warnings
772 warnings.warn(
773 'sysconfig.expand_makefile_vars is deprecated and will be removed in '
774 'Python 3.16. Use sysconfig.get_paths(vars=...) instead.',
775 DeprecationWarning,
776 stacklevel=2,
777 )
778
779 import re
780
781 _findvar1_rx = r"\$\(([A-Za-z][A-Za-z0-9_]*)\)"
782 _findvar2_rx = r"\${([A-Za-z][A-Za-z0-9_]*)}"
783
784 # This algorithm does multiple expansion, so if vars['foo'] contains
785 # "${bar}", it will expand ${foo} to ${bar}, and then expand
786 # ${bar}... and so forth. This is fine as long as 'vars' comes from
787 # 'parse_makefile()', which takes care of such expansions eagerly,
788 # according to make's variable expansion semantics.
789
790 while True:
791 m = re.search(_findvar1_rx, s) or re.search(_findvar2_rx, s)
792 if m:
793 (beg, end) = m.span()
794 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
795 else:
796 break
797 return s