Debian Codegraph @

Lib/sysconfig/__init__.py

raw ◀ ▶
Source reconstructed at patch state 1 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 '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 # Always convert srcdir to an absolute path
549 srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
550 if os.name == 'posix':
551 if _PYTHON_BUILD:
552 # If srcdir is a relative path (typically '.' or '..')
553 # then it should be interpreted relative to the directory
554 # containing Makefile.
555 base = os.path.dirname(get_makefile_filename())
556 srcdir = os.path.join(base, srcdir)
557 else:
558 # srcdir is not meaningful since the installation is
559 # spread about the filesystem. We choose the
560 # directory containing the Makefile since we know it
561 # exists.
562 srcdir = os.path.dirname(get_makefile_filename())
563 _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
564
565 # OS X platforms require special customization to handle
566 # multi-architecture, multi-os-version installers
567 if sys.platform == 'darwin':
568 import _osx_support
569 _osx_support.customize_config_vars(_CONFIG_VARS)
570
571 global _CONFIG_VARS_INITIALIZED
572 _CONFIG_VARS_INITIALIZED = True
573
574
575 def get_config_vars(*args):
576 """With no arguments, return a dictionary of all configuration
577 variables relevant for the current platform.
578
579 On Unix, this means every variable defined in Python's installed Makefile;
580 On Windows it's a much smaller set.
581
582 With arguments, return a list of values that result from looking up
583 each argument in the configuration variable dictionary.
584 """
585 global _CONFIG_VARS_INITIALIZED
586
587 # Avoid claiming the lock once initialization is complete.
588 if not _CONFIG_VARS_INITIALIZED:
589 with _CONFIG_VARS_LOCK:
590 # Test again with the lock held to avoid races. Note that
591 # we test _CONFIG_VARS here, not _CONFIG_VARS_INITIALIZED,
592 # to ensure that recursive calls to get_config_vars()
593 # don't re-enter init_config_vars().
594 if _CONFIG_VARS is None:
595 _init_config_vars()
596 else:
597 # If the site module initialization happened after _CONFIG_VARS was
598 # initialized, a virtual environment might have been activated, resulting in
599 # variables like sys.prefix changing their value, so we need to re-init the
600 # config vars (see GH-126789).
601 if _CONFIG_VARS['base'] != os.path.normpath(sys.prefix):
602 with _CONFIG_VARS_LOCK:
603 _CONFIG_VARS_INITIALIZED = False
604 _init_config_vars()
605
606 if args:
607 vals = []
608 for name in args:
609 vals.append(_CONFIG_VARS.get(name))
610 return vals
611 else:
612 return _CONFIG_VARS
613
614
615 def get_config_var(name):
616 """Return the value of a single variable using the dictionary returned by
617 'get_config_vars()'.
618
619 Equivalent to get_config_vars().get(name)
620 """
621 return get_config_vars().get(name)
622
623
624 def get_platform():
625 """Return a string that identifies the current platform.
626
627 This is used mainly to distinguish platform-specific build directories and
628 platform-specific built distributions. Typically includes the OS name and
629 version and the architecture (as supplied by 'os.uname()'), although the
630 exact information included depends on the OS; on Linux, the kernel version
631 isn't particularly important.
632
633 Examples of returned values:
634
635
636 Windows:
637
638 - win-amd64 (64-bit Windows on AMD64, aka x86_64, Intel64, and EM64T)
639 - win-arm64 (64-bit Windows on ARM64, aka AArch64)
640 - win32 (all others - specifically, sys.platform is returned)
641
642 POSIX based OS:
643
644 - linux-x86_64
645 - macosx-15.5-arm64
646 - macosx-26.0-universal2 (macOS on Apple Silicon or Intel)
647 - android-24-arm64_v8a
648
649 For other non-POSIX platforms, currently just returns :data:`sys.platform`."""
650 if os.name == 'nt':
651 if 'amd64' in sys.version.lower():
652 return 'win-amd64'
653 if '(arm)' in sys.version.lower():
654 return 'win-arm32'
655 if '(arm64)' in sys.version.lower():
656 return 'win-arm64'
657 return sys.platform
658
659 if os.name != "posix" or not hasattr(os, 'uname'):
660 # XXX what about the architecture? NT is Intel or Alpha
661 return sys.platform
662
663 # Set for cross builds explicitly
664 if "_PYTHON_HOST_PLATFORM" in os.environ:
665 return os.environ["_PYTHON_HOST_PLATFORM"]
666
667 # Try to distinguish various flavours of Unix
668 osname, host, release, version, machine = os.uname()
669
670 # Convert the OS name to lowercase, remove '/' characters, and translate
671 # spaces (for "Power Macintosh")
672 osname = osname.lower().replace('/', '')
673 machine = machine.replace(' ', '_')
674 machine = machine.replace('/', '-')
675
676 if osname[:5] == "linux":
677 if sys.platform == "android":
678 osname = "android"
679 release = get_config_var("ANDROID_API_LEVEL")
680
681 # Wheel tags use the ABI names from Android's own tools.
682 machine = {
683 "x86_64": "x86_64",
684 "i686": "x86",
685 "aarch64": "arm64_v8a",
686 "armv7l": "armeabi_v7a",
687 }[machine]
688 else:
689 # At least on Linux/Intel, 'machine' is the processor --
690 # i386, etc.
691 # XXX what about Alpha, SPARC, etc?
692 return f"{osname}-{machine}"
693 elif osname[:5] == "sunos":
694 if release[0] >= "5": # SunOS 5 == Solaris 2
695 osname = "solaris"
696 release = f"{int(release[0]) - 3}.{release[2:]}"
697 # We can't use "platform.architecture()[0]" because a
698 # bootstrap problem. We use a dict to get an error
699 # if some suspicious happens.
700 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
701 machine += f".{bitness[sys.maxsize]}"
702 # fall through to standard osname-release-machine representation
703 elif osname[:3] == "aix":
704 from _aix_support import aix_platform
705 return aix_platform()
706 elif osname[:6] == "cygwin":
707 osname = "cygwin"
708 import re
709 rel_re = re.compile(r'[\d.]+')
710 m = rel_re.match(release)
711 if m:
712 release = m.group()
713 elif osname[:6] == "darwin":
714 if sys.platform == "ios":
715 release = get_config_vars().get("IPHONEOS_DEPLOYMENT_TARGET", "13.0")
716 osname = sys.platform
717 machine = sys.implementation._multiarch
718 else:
719 import _osx_support
720 osname, release, machine = _osx_support.get_platform_osx(
721 get_config_vars(),
722 osname, release, machine)
723
724 return f"{osname}-{release}-{machine}"
725
726
727 def get_python_version():
728 return _PY_VERSION_SHORT
729
730
731 def _get_python_version_abi():
732 return _PY_VERSION_SHORT + get_config_var("abi_thread")
733
734
735 def expand_makefile_vars(s, vars):
736 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
737 'string' according to 'vars' (a dictionary mapping variable names to
738 values). Variables not present in 'vars' are silently expanded to the
739 empty string. The variable values in 'vars' should not contain further
740 variable expansions; if 'vars' is the output of 'parse_makefile()',
741 you're fine. Returns a variable-expanded version of 's'.
742 """
743 import re
744
745 _findvar1_rx = r"\$\(([A-Za-z][A-Za-z0-9_]*)\)"
746 _findvar2_rx = r"\${([A-Za-z][A-Za-z0-9_]*)}"
747
748 # This algorithm does multiple expansion, so if vars['foo'] contains
749 # "${bar}", it will expand ${foo} to ${bar}, and then expand
750 # ${bar}... and so forth. This is fine as long as 'vars' comes from
751 # 'parse_makefile()', which takes care of such expansions eagerly,
752 # according to make's variable expansion semantics.
753
754 while True:
755 m = re.search(_findvar1_rx, s) or re.search(_findvar2_rx, s)
756 if m:
757 (beg, end) = m.span()
758 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
759 else:
760 break
761 return s