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