Debian Codegraph @

Lib/sysconfig/__init__.py

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