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 # 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 multiarch = get_config_var('MULTIARCH')
603 if multiarch:
604 _CONFIG_VARS['multiarchsubdir'] = '/' + multiarch
605 else:
606 _CONFIG_VARS['multiarchsubdir'] = ''
607
608 # Always convert srcdir to an absolute path
609 srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
610 if os.name == 'posix':
611 if _PYTHON_BUILD:
612 # If srcdir is a relative path (typically '.' or '..')
613 # then it should be interpreted relative to the directory
614 # containing Makefile.
615 base = os.path.dirname(get_makefile_filename())
616 srcdir = os.path.join(base, srcdir)
617 else:
618 # srcdir is not meaningful since the installation is
619 # spread about the filesystem. We choose the
620 # directory containing the Makefile since we know it
621 # exists.
622 srcdir = os.path.dirname(get_makefile_filename())
623 _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
624
625 # OS X platforms require special customization to handle
626 # multi-architecture, multi-os-version installers
627 if sys.platform == 'darwin':
628 import _osx_support
629 _osx_support.customize_config_vars(_CONFIG_VARS)
630
631 global _CONFIG_VARS_INITIALIZED
632 _CONFIG_VARS_INITIALIZED = True
633
634
635 def get_config_vars(*args):
636 """With no arguments, return a dictionary of all configuration
637 variables relevant for the current platform.
638
639 On Unix, this means every variable defined in Python's installed Makefile;
640 On Windows it's a much smaller set.
641
642 With arguments, return a list of values that result from looking up
643 each argument in the configuration variable dictionary.
644 """
645 global _CONFIG_VARS_INITIALIZED
646
647 # Avoid claiming the lock once initialization is complete.
648 if _CONFIG_VARS_INITIALIZED:
649 # GH-126789: If sys.prefix or sys.exec_prefix were updated, invalidate the cache.
650 prefix = os.path.normpath(sys.prefix)
651 exec_prefix = os.path.normpath(sys.exec_prefix)
652 if _CONFIG_VARS['prefix'] != prefix or _CONFIG_VARS['exec_prefix'] != exec_prefix:
653 with _CONFIG_VARS_LOCK:
654 _CONFIG_VARS_INITIALIZED = False
655 _init_config_vars()
656 else:
657 # Initialize the config_vars cache.
658 with _CONFIG_VARS_LOCK:
659 # Test again with the lock held to avoid races. Note that
660 # we test _CONFIG_VARS here, not _CONFIG_VARS_INITIALIZED,
661 # to ensure that recursive calls to get_config_vars()
662 # don't re-enter init_config_vars().
663 if _CONFIG_VARS is None:
664 _init_config_vars()
665
666 if args:
667 vals = []
668 for name in args:
669 vals.append(_CONFIG_VARS.get(name))
670 return vals
671 else:
672 return _CONFIG_VARS
673
674
675 def get_config_var(name):
676 """Return the value of a single variable using the dictionary returned by
677 'get_config_vars()'.
678
679 Equivalent to get_config_vars().get(name)
680 """
681 return get_config_vars().get(name)
682
683
684 def get_platform():
685 """Return a string that identifies the current platform.
686
687 This is used mainly to distinguish platform-specific build directories and
688 platform-specific built distributions. Typically includes the OS name and
689 version and the architecture (as supplied by 'os.uname()'), although the
690 exact information included depends on the OS; on Linux, the kernel version
691 isn't particularly important.
692
693 Examples of returned values:
694
695
696 Windows:
697
698 - win-amd64 (64-bit Windows on AMD64, aka x86_64, Intel64, and EM64T)
699 - win-arm64 (64-bit Windows on ARM64, aka AArch64)
700 - win32 (all others - specifically, sys.platform is returned)
701
702 POSIX based OS:
703
704 - linux-x86_64
705 - macosx-15.5-arm64
706 - macosx-26.0-universal2 (macOS on Apple Silicon or Intel)
707 - android-24-arm64_v8a
708
709 For other non-POSIX platforms, currently just returns :data:`sys.platform`."""
710 if os.name == 'nt':
711 if 'amd64' in sys.version.lower():
712 return 'win-amd64'
713 if '(arm)' in sys.version.lower():
714 return 'win-arm32'
715 if '(arm64)' in sys.version.lower():
716 return 'win-arm64'
717 return sys.platform
718
719 if os.name != "posix" or not hasattr(os, 'uname'):
720 # XXX what about the architecture? NT is Intel or Alpha
721 return sys.platform
722
723 # Set for cross builds explicitly
724 if "_PYTHON_HOST_PLATFORM" in os.environ:
725 osname, _, machine = os.environ["_PYTHON_HOST_PLATFORM"].partition('-')
726 release = None
727 else:
728 # Try to distinguish various flavours of Unix
729 osname, host, release, version, machine = os.uname()
730
731 # Convert the OS name to lowercase, remove '/' characters, and translate
732 # spaces (for "Power Macintosh")
733 osname = osname.lower().replace('/', '')
734 machine = machine.replace(' ', '_')
735 machine = machine.replace('/', '-')
736
737 if osname == "android" or sys.platform == "android":
738 osname = "android"
739 release = get_config_var("ANDROID_API_LEVEL")
740
741 # Wheel tags use the ABI names from Android's own tools.
742 # When Python is running on 32-bit ARM Android on a 64-bit ARM kernel,
743 # 'os.uname().machine' is 'armv8l'. Such devices run the same userspace
744 # code as 'armv7l' devices.
745 # During the build process of the Android testbed when targeting 32-bit ARM,
746 # '_PYTHON_HOST_PLATFORM' is 'arm-linux-androideabi', so 'machine' becomes
747 # 'arm'.
748 machine = {
749 "aarch64": "arm64_v8a",
750 "arm": "armeabi_v7a",
751 "armv7l": "armeabi_v7a",
752 "armv8l": "armeabi_v7a",
753 "i686": "x86",
754 "x86_64": "x86_64",
755 }[machine]
756 elif osname == "linux":
757 # At least on Linux/Intel, 'machine' is the processor --
758 # i386, etc.
759 # XXX what about Alpha, SPARC, etc?
760 return f"{osname}-{machine}"
761 elif osname[:5] == "sunos":
762 if release[0] >= "5": # SunOS 5 == Solaris 2
763 osname = "solaris"
764 release = f"{int(release[0]) - 3}.{release[2:]}"
765 # We can't use "platform.architecture()[0]" because a
766 # bootstrap problem. We use a dict to get an error
767 # if some suspicious happens.
768 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
769 machine += f".{bitness[sys.maxsize]}"
770 # fall through to standard osname-release-machine representation
771 elif osname[:3] == "aix":
772 from _aix_support import aix_platform
773 return aix_platform()
774 elif osname[:6] == "cygwin":
775 osname = "cygwin"
776 import re
777 rel_re = re.compile(r'[\d.]+')
778 m = rel_re.match(release)
779 if m:
780 release = m.group()
781 elif osname[:6] == "darwin":
782 if sys.platform == "ios":
783 release = get_config_vars().get("IPHONEOS_DEPLOYMENT_TARGET", "13.0")
784 osname = sys.platform
785 machine = sys.implementation._multiarch
786 else:
787 import _osx_support
788 osname, release, machine = _osx_support.get_platform_osx(
789 get_config_vars(),
790 osname, release, machine)
791
792 return '-'.join(map(str, filter(None, (osname, release, machine))))
793
794
795 def get_python_version():
796 return _PY_VERSION_SHORT
797
798
799 def _get_python_version_abi():
800 return _PY_VERSION_SHORT + get_config_var("abi_thread")
801
802
803 def expand_makefile_vars(s, vars):
804 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
805 'string' according to 'vars' (a dictionary mapping variable names to
806 values). Variables not present in 'vars' are silently expanded to the
807 empty string. The variable values in 'vars' should not contain further
808 variable expansions; if 'vars' is the output of 'parse_makefile()',
809 you're fine. Returns a variable-expanded version of 's'.
810 """
811
812 import warnings
813 warnings.warn(
814 'sysconfig.expand_makefile_vars is deprecated and will be removed in '
815 'Python 3.16. Use sysconfig.get_paths(vars=...) instead.',
816 DeprecationWarning,
817 stacklevel=2,
818 )
819
820 import re
821
822 _findvar1_rx = r"\$\(([A-Za-z][A-Za-z0-9_]*)\)"
823 _findvar2_rx = r"\${([A-Za-z][A-Za-z0-9_]*)}"
824
825 # This algorithm does multiple expansion, so if vars['foo'] contains
826 # "${bar}", it will expand ${foo} to ${bar}, and then expand
827 # ${bar}... and so forth. This is fine as long as 'vars' comes from
828 # 'parse_makefile()', which takes care of such expansions eagerly,
829 # according to make's variable expansion semantics.
830
831 while True:
832 m = re.search(_findvar1_rx, s) or re.search(_findvar2_rx, s)
833 if m:
834 (beg, end) = m.span()
835 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
836 else:
837 break
838 return s