Debian Codegraph @

lib-python/3/sysconfig.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 """Access to Python's configuration information."""
2
3 import os
4 import sys
5 from os.path import pardir, realpath
6
7 __all__ = [
8 'get_config_h_filename',
9 'get_config_var',
10 'get_config_vars',
11 'get_makefile_filename',
12 'get_path',
13 'get_path_names',
14 'get_paths',
15 'get_platform',
16 'get_python_version',
17 'get_scheme_names',
18 'parse_config_h',
19 ]
20
21 # Keys for get_config_var() that are never converted to Python integers.
22 _ALWAYS_STR = {
23 'MACOSX_DEPLOYMENT_TARGET',
24 }
25
26 _INSTALL_SCHEMES = {
27 'posix_prefix': {
28 'stdlib': '{installed_base}/{platlibdir}/{implementation_lower}{py_version_short}',
29 'platstdlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}',
30 'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',
31 'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}/site-packages',
32 'include':
33 '{installed_base}/include/{implementation_lower}{py_version_short}{abiflags}',
34 'platinclude':
35 '{installed_platbase}/include/{implementation_lower}{py_version_short}{abiflags}',
36 'scripts': '{base}/bin',
37 'data': '{base}',
38 },
39 'posix_home': {
40 'stdlib': '{installed_base}/lib/{implementation_lower}',
41 'platstdlib': '{base}/lib/{implementation_lower}',
42 'purelib': '{base}/lib/{implementation_lower}',
43 'platlib': '{base}/lib/{implementation_lower}',
44 'include': '{installed_base}/include/{implementation_lower}',
45 'platinclude': '{installed_base}/include/{implementation_lower}',
46 'scripts': '{base}/bin',
47 'data': '{base}',
48 },
49 'nt': {
50 'stdlib': '{installed_base}/Lib',
51 'platstdlib': '{base}/Lib',
52 'purelib': '{base}/Lib/site-packages',
53 'platlib': '{base}/Lib/site-packages',
54 'include': '{installed_base}/Include',
55 'platinclude': '{installed_base}/Include',
56 'scripts': '{base}/Scripts',
57 'data': '{base}',
58 },
59 # Downstream distributors can overwrite the default install scheme.
60 # This is done to support downstream modifications where distributors change
61 # the installation layout (eg. different site-packages directory).
62 # So, distributors will change the default scheme to one that correctly
63 # represents their layout.
64 # This presents an issue for projects/people that need to bootstrap virtual
65 # environments, like virtualenv. As distributors might now be customizing
66 # the default install scheme, there is no guarantee that the information
67 # returned by sysconfig.get_default_scheme/get_paths is correct for
68 # a virtual environment, the only guarantee we have is that it is correct
69 # for the *current* environment. When bootstrapping a virtual environment,
70 # we need to know its layout, so that we can place the files in the
71 # correct locations.
72 # The "*_venv" install scheme is a scheme to bootstrap virtual environments,
73 # essentially identical to the default posix_prefix/nt schemes.
74 # Downstream distributors who patch posix_prefix/nt scheme are encouraged to
75 # leave the following schemes unchanged
76 'posix_venv': {
77 'stdlib': '{installed_base}/{platlibdir}/{implementation_lower}{py_version_short}',
78 'platstdlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}',
79 'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',
80 'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}/site-packages',
81 'include':
82 '{installed_base}/include/{implementation_lower}{py_version_short}{abiflags}',
83 'platinclude':
84 '{installed_platbase}/include/{implementation_lower}{py_version_short}{abiflags}',
85 'scripts': '{base}/bin',
86 'data': '{base}',
87 },
88 'nt_venv': {
89 'stdlib': '{installed_base}/Lib',
90 'platstdlib': '{base}/Lib',
91 'purelib': '{base}/Lib/site-packages',
92 'platlib': '{base}/Lib/site-packages',
93 'include': '{installed_base}/Include',
94 'platinclude': '{installed_base}/Include',
95 'scripts': '{base}/Scripts',
96 'data': '{base}',
97 },
98 }
99
100 # For the OS-native venv scheme, we essentially provide an alias:
101 if os.name == 'nt':
102 _INSTALL_SCHEMES['venv'] = _INSTALL_SCHEMES['nt_venv']
103 else:
104 _INSTALL_SCHEMES['venv'] = _INSTALL_SCHEMES['posix_venv']
105
106
107 # NOTE: site.py has copy of this function.
108 # Sync it when modify this function.
109 def _get_implementation():
110 if sys.implementation.name == 'pypy':
111 return 'PyPy'
112 return 'Python'
113
114
115 # NOTE: site.py has copy of this function.
116 # Sync it when modify this function.
117 def _getuserbase():
118 env_base = os.environ.get("PYTHONUSERBASE", None)
119 if env_base:
120 return env_base
121
122 # Emscripten, VxWorks, and WASI have no home directories
123 if sys.platform in {"emscripten", "vxworks", "wasi"}:
124 return None
125
126 def joinuser(*args):
127 return os.path.expanduser(os.path.join(*args))
128
129 if os.name == "nt":
130 base = os.environ.get("APPDATA") or "~"
131 return joinuser(base, _get_implementation())
132
133 if sys.platform == "darwin" and sys._framework:
134 return joinuser("~", "Library", sys._framework,
135 f"{sys.version_info[0]}.{sys.version_info[1]}")
136
137 return joinuser("~", ".local")
138
139 _HAS_USER_BASE = (_getuserbase() is not None)
140
141 if _HAS_USER_BASE:
142 _INSTALL_SCHEMES |= {
143 # NOTE: When modifying "purelib" scheme, update site._get_path() too.
144 'nt_user': {
145 'stdlib': '{userbase}/{implementation}{py_version_nodot_plat}',
146 'platstdlib': '{userbase}/{implementation}{py_version_nodot_plat}',
147 'purelib': '{userbase}/{implementation}{py_version_nodot_plat}/site-packages',
148 'platlib': '{userbase}/{implementation}{py_version_nodot_plat}/site-packages',
149 'include': '{userbase}/{implementation}{py_version_nodot_plat}/Include',
150 'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
151 'data': '{userbase}',
152 },
153 'posix_user': {
154 'stdlib': '{userbase}/{platlibdir}/{implementation_lower}{py_version_short}',
155 'platstdlib': '{userbase}/{platlibdir}/{implementation_lower}{py_version_short}',
156 'purelib': '{userbase}/lib/{implementation_lower}{py_version_short}/site-packages',
157 'platlib': '{userbase}/{platlibdir}/{implementation_lower}{py_version_short}/site-packages',
158 'include': '{userbase}/include/{implementation_lower}{py_version_short}',
159 'scripts': '{userbase}/bin',
160 'data': '{userbase}',
161 },
162 'osx_framework_user': {
163 'stdlib': '{userbase}/lib/{implementation_lower}',
164 'platstdlib': '{userbase}/lib/{implementation_lower}',
165 'purelib': '{userbase}/lib/{implementation_lower}/site-packages',
166 'platlib': '{userbase}/lib/{implementation_lower}/site-packages',
167 'include': '{userbase}/include/{implementation_lower}{py_version_short}',
168 'scripts': '{userbase}/bin',
169 'data': '{userbase}',
170 },
171 }
172
173 _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
174 'scripts', 'data')
175
176 _PY_VERSION = sys.version.split()[0]
177 _PY_VERSION_SHORT = f'{sys.version_info[0]}.{sys.version_info[1]}'
178 _PY_VERSION_SHORT_NO_DOT = f'{sys.version_info[0]}{sys.version_info[1]}'
179 _PREFIX = os.path.normpath(sys.prefix)
180 _BASE_PREFIX = os.path.normpath(sys.base_prefix)
181 _EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
182 _BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
183 _CONFIG_VARS = None
184 _USER_BASE = None
185
186 # Regexes needed for parsing Makefile (and similar syntaxes,
187 # like old-style Setup files).
188 _variable_rx = r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)"
189 _findvar1_rx = r"\$\(([A-Za-z][A-Za-z0-9_]*)\)"
190 _findvar2_rx = r"\${([A-Za-z][A-Za-z0-9_]*)}"
191
192
193 def _safe_realpath(path):
194 try:
195 return realpath(path)
196 except OSError:
197 return path
198
199 if sys.executable:
200 _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
201 else:
202 # sys.executable can be empty if argv[0] has been changed and Python is
203 # unable to retrieve the real program name
204 _PROJECT_BASE = _safe_realpath(os.getcwd())
205
206 # In a virtual environment, `sys._home` gives us the target directory
207 # `_PROJECT_BASE` for the executable that created it when the virtual
208 # python is an actual executable ('venv --copies' or Windows).
209 _sys_home = getattr(sys, '_home', None)
210 if _sys_home:
211 _PROJECT_BASE = _sys_home
212
213 if os.name == 'nt':
214 # In a source build, the executable is in a subdirectory of the root
215 # that we want (<root>\PCbuild\<platname>).
216 # `_BASE_PREFIX` is used as the base installation is where the source
217 # will be. The realpath is needed to prevent mount point confusion
218 # that can occur with just string comparisons.
219 if _safe_realpath(_PROJECT_BASE).startswith(
220 _safe_realpath(f'{_BASE_PREFIX}\\PCbuild')):
221 _PROJECT_BASE = _BASE_PREFIX
222
223 # set for cross builds
224 if "_PYTHON_PROJECT_BASE" in os.environ:
225 _PROJECT_BASE = _safe_realpath(os.environ["_PYTHON_PROJECT_BASE"])
226
227 def is_python_build(check_home=None):
228 if check_home is not None:
229 import warnings
230 warnings.warn("check_home argument is deprecated and ignored.",
231 DeprecationWarning, stacklevel=2)
232 for fn in ("Setup", "Setup.local"):
233 if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)):
234 return True
235 return False
236
237 _PYTHON_BUILD = is_python_build()
238
239 if _PYTHON_BUILD:
240 for scheme in ('posix_prefix', 'posix_home'):
241 # On POSIX-y platforms, Python will:
242 # - Build from .h files in 'headers' (which is only added to the
243 # scheme when building CPython)
244 # - Install .h files to 'include'
245 scheme = _INSTALL_SCHEMES[scheme]
246 scheme['headers'] = scheme['include']
247 scheme['include'] = '{srcdir}/Include'
248 scheme['platinclude'] = '{projectbase}/.'
249 del scheme
250
251
252 def _subst_vars(s, local_vars):
253 try:
254 return s.format(**local_vars)
255 except KeyError as var:
256 try:
257 return s.format(**os.environ)
258 except KeyError:
259 raise AttributeError(f'{var}') from None
260
261 def _extend_dict(target_dict, other_dict):
262 target_keys = target_dict.keys()
263 for key, value in other_dict.items():
264 if key in target_keys:
265 continue
266 target_dict[key] = value
267
268
269 def _expand_vars(scheme, vars):
270 res = {}
271 if vars is None:
272 vars = {}
273 _extend_dict(vars, get_config_vars())
274 if os.name == 'nt':
275 # On Windows we want to substitute 'lib' for schemes rather
276 # than the native value (without modifying vars, in case it
277 # was passed in)
278 vars = vars | {'platlibdir': 'lib'}
279
280 for key, value in _INSTALL_SCHEMES[scheme].items():
281 if os.name in ('posix', 'nt'):
282 value = os.path.expanduser(value)
283 res[key] = os.path.normpath(_subst_vars(value, vars))
284 return res
285
286
287 def _get_preferred_schemes():
288 if os.name == 'nt':
289 return {
290 'prefix': 'nt',
291 'home': 'posix_home',
292 'user': 'nt_user',
293 }
294 if sys.platform == 'darwin' and sys._framework:
295 return {
296 'prefix': 'posix_prefix',
297 'home': 'posix_home',
298 'user': 'osx_framework_user',
299 }
300 return {
301 'prefix': 'posix_prefix',
302 'home': 'posix_home',
303 'user': 'posix_user',
304 }
305
306
307 def get_preferred_scheme(key):
308 if key == 'prefix' and sys.prefix != sys.base_prefix:
309 return 'venv'
310 scheme = _get_preferred_schemes()[key]
311 if scheme not in _INSTALL_SCHEMES:
312 raise ValueError(
313 f"{key!r} returned {scheme!r}, which is not a valid scheme "
314 f"on this platform"
315 )
316 return scheme
317
318
319 def get_default_scheme():
320 return get_preferred_scheme('prefix')
321
322
323 def _parse_makefile(filename, vars=None, keep_unresolved=True):
324 """Parse a Makefile-style file.
325
326 A dictionary containing name/value pairs is returned. If an
327 optional dictionary is passed in as the second argument, it is
328 used instead of a new dictionary.
329 """
330 import re
331
332 if vars is None:
333 vars = {}
334 done = {}
335 notdone = {}
336
337 with open(filename, encoding=sys.getfilesystemencoding(),
338 errors="surrogateescape") as f:
339 lines = f.readlines()
340
341 for line in lines:
342 if line.startswith('#') or line.strip() == '':
343 continue
344 m = re.match(_variable_rx, line)
345 if m:
346 n, v = m.group(1, 2)
347 v = v.strip()
348 # `$$' is a literal `$' in make
349 tmpv = v.replace('$$', '')
350
351 if "$" in tmpv:
352 notdone[n] = v
353 else:
354 try:
355 if n in _ALWAYS_STR:
356 raise ValueError
357
358 v = int(v)
359 except ValueError:
360 # insert literal `$'
361 done[n] = v.replace('$$', '$')
362 else:
363 done[n] = v
364
365 # do variable interpolation here
366 variables = list(notdone.keys())
367
368 # Variables with a 'PY_' prefix in the makefile. These need to
369 # be made available without that prefix through sysconfig.
370 # Special care is needed to ensure that variable expansion works, even
371 # if the expansion uses the name without a prefix.
372 renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
373
374 while len(variables) > 0:
375 for name in tuple(variables):
376 value = notdone[name]
377 m1 = re.search(_findvar1_rx, value)
378 m2 = re.search(_findvar2_rx, value)
379 if m1 and m2:
380 m = m1 if m1.start() < m2.start() else m2
381 else:
382 m = m1 if m1 else m2
383 if m is not None:
384 n = m.group(1)
385 found = True
386 if n in done:
387 item = str(done[n])
388 elif n in notdone:
389 # get it on a subsequent round
390 found = False
391 elif n in os.environ:
392 # do it like make: fall back to environment
393 item = os.environ[n]
394
395 elif n in renamed_variables:
396 if (name.startswith('PY_') and
397 name[3:] in renamed_variables):
398 item = ""
399
400 elif 'PY_' + n in notdone:
401 found = False
402
403 else:
404 item = str(done['PY_' + n])
405
406 else:
407 done[n] = item = ""
408
409 if found:
410 after = value[m.end():]
411 value = value[:m.start()] + item + after
412 if "$" in after:
413 notdone[name] = value
414 else:
415 try:
416 if name in _ALWAYS_STR:
417 raise ValueError
418 value = int(value)
419 except ValueError:
420 done[name] = value.strip()
421 else:
422 done[name] = value
423 variables.remove(name)
424
425 if name.startswith('PY_') \
426 and name[3:] in renamed_variables:
427
428 name = name[3:]
429 if name not in done:
430 done[name] = value
431
432 else:
433 # Adds unresolved variables to the done dict.
434 # This is disabled when called from distutils.sysconfig
435 if keep_unresolved:
436 done[name] = value
437 # bogus variable reference (e.g. "prefix=$/opt/python");
438 # just drop it since we can't deal
439 variables.remove(name)
440
441 # strip spurious spaces
442 for k, v in done.items():
443 if isinstance(v, str):
444 done[k] = v.strip()
445
446 # save the results in the global dictionary
447 vars.update(done)
448 return vars
449
450
451 def get_makefile_filename():
452 """Return the path of the Makefile."""
453 if _PYTHON_BUILD:
454 return os.path.join(_PROJECT_BASE, "Makefile")
455 if hasattr(sys, 'abiflags'):
456 config_dir_name = f'config-{_PY_VERSION_SHORT}{sys.abiflags}'
457 else:
458 config_dir_name = 'config'
459 if hasattr(sys.implementation, '_multiarch'):
460 config_dir_name += f'-{sys.implementation._multiarch}'
461 return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
462
463
464 def _get_sysconfigdata_name():
465 multiarch = getattr(sys.implementation, '_multiarch', '')
466 return os.environ.get(
467 '_PYTHON_SYSCONFIGDATA_NAME',
468 f'_sysconfigdata_{sys.abiflags}_{sys.platform}_{multiarch}',
469 )
470
471
472 def _generate_posix_vars(args):
473 """Generate the Python module containing build-time variables."""
474 import pprint
475 vars = {}
476 if sys.implementation.name == 'pypy':
477 import _sysconfigdata
478 vars = _sysconfigdata.build_time_vars
479 else:
480 # load the installed Makefile:
481 makefile = get_makefile_filename()
482 try:
483 _parse_makefile(makefile, vars)
484 except OSError as e:
485 msg = f"invalid Python installation: unable to open {makefile}"
486 if hasattr(e, "strerror"):
487 msg = f"{msg} ({e.strerror})"
488 raise OSError(msg)
489 # load the installed pyconfig.h:
490 config_h = get_config_h_filename()
491 try:
492 with open(config_h, encoding="utf-8") as f:
493 parse_config_h(f, vars)
494 except OSError as e:
495 msg = f"invalid Python installation: unable to open {config_h}"
496 if hasattr(e, "strerror"):
497 msg = f"{msg} ({e.strerror})"
498 raise OSError(msg)
499 # On AIX, there are wrong paths to the linker scripts in the Makefile
500 # -- these paths are relative to the Python source, but when installed
501 # the scripts are in another directory.
502 if _PYTHON_BUILD:
503 vars['BLDSHARED'] = vars['LDSHARED']
504
505 if args:
506 # PyPy extension: they should be key, value pairs
507 for k, v in zip(args[::2], args[1::2]):
508 vars[k] = v
509 # There's a chicken-and-egg situation on OS X with regards to the
510 # _sysconfigdata module after the changes introduced by #15298:
511 # get_config_vars() is called by get_platform() as part of the
512 # `make pybuilddir.txt` target -- which is a precursor to the
513 # _sysconfigdata.py module being constructed. Unfortunately,
514 # get_config_vars() eventually calls _init_posix(), which attempts
515 # to import _sysconfigdata, which we won't have built yet. In order
516 # for _init_posix() to work, if we're on Darwin, just mock up the
517 # _sysconfigdata module manually and populate it with the build vars.
518 # This is more than sufficient for ensuring the subsequent call to
519 # get_platform() succeeds.
520 name = _get_sysconfigdata_name()
521 if 'darwin' in sys.platform:
522 import types
523 module = types.ModuleType(name)
524 module.build_time_vars = vars
525 sys.modules[name] = module
526
527 pybuilddir = f'build/lib.{get_platform()}-{_PY_VERSION_SHORT}'
528 if hasattr(sys, "gettotalrefcount"):
529 pybuilddir += '-pydebug'
530 os.makedirs(pybuilddir, exist_ok=True)
531 destfile = os.path.join(pybuilddir, name + '.py')
532
533 with open(destfile, 'w', encoding='utf8') as f:
534 f.write('# system configuration generated and used by'
535 ' the sysconfig module\n')
536 f.write('build_time_vars = ')
537 pprint.pprint(vars, stream=f)
538
539 # Create file used for sys.path fixup -- see Modules/getpath.c
540 with open('pybuilddir.txt', 'w', encoding='utf8') as f:
541 f.write(pybuilddir)
542
543 def _init_posix(vars):
544 """Initialize the module as appropriate for POSIX systems."""
545 # CPython: _sysconfigdata_* is generated at build time, see _generate_posix_vars()
546 # name = _get_sysconfigdata_name()
547 # PyPy: _sysconfigdata is a dynamic module (uses sys to determine values),
548 # while _sysconfigdata_* is a static version of the same values
549 # generated by calling _generate_posix_vars as part of packaging.py.
550 # To prevent chicken-and-egg problems of needing the values before
551 # generating them, fall back to the dynamic version here.
552 name = _get_sysconfigdata_name()
553 try:
554 _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
555 except ImportError:
556 if '_PYTHON_SYSCONFIGDATA_NAME' in os.environ:
557 raise
558 _temp = __import__("_sysconfigdata", globals(), locals(), ['build_time_vars'], 0)
559
560 build_time_vars = _temp.build_time_vars
561 vars.update(build_time_vars)
562
563 def _init_non_posix(vars):
564 """Initialize the module as appropriate for NT"""
565 # set basic install directories
566 import _imp
567 vars['LIBDEST'] = get_path('stdlib')
568 vars['BINLIBDEST'] = get_path('platstdlib')
569 vars['INCLUDEPY'] = get_path('include')
570 vars['EXT_SUFFIX'] = _imp.extension_suffixes()[0]
571 vars['EXE'] = '.exe'
572 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
573 vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
574 vars['TZPATH'] = ''
575 # pypy: give us control over the ABI tag in a wheel name
576 so_ext = _imp.extension_suffixes()[0]
577 vars['SOABI']= '-'.join(so_ext.split('.')[1].split('-')[:2])
578
579 #
580 # public APIs
581 #
582
583
584 def parse_config_h(fp, vars=None):
585 """Parse a config.h-style file.
586
587 A dictionary containing name/value pairs is returned. If an
588 optional dictionary is passed in as the second argument, it is
589 used instead of a new dictionary.
590 """
591 if vars is None:
592 vars = {}
593 import re
594 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
595 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
596
597 while True:
598 line = fp.readline()
599 if not line:
600 break
601 m = define_rx.match(line)
602 if m:
603 n, v = m.group(1, 2)
604 try:
605 if n in _ALWAYS_STR:
606 raise ValueError
607 v = int(v)
608 except ValueError:
609 pass
610 vars[n] = v
611 else:
612 m = undef_rx.match(line)
613 if m:
614 vars[m.group(1)] = 0
615 return vars
616
617
618 def get_config_h_filename():
619 """Return the path of pyconfig.h."""
620 if _PYTHON_BUILD:
621 if os.name == "nt":
622 inc_dir = os.path.join(_PROJECT_BASE, "PC")
623 else:
624 inc_dir = _PROJECT_BASE
625 else:
626 inc_dir = get_path('platinclude')
627 return os.path.join(inc_dir, 'pyconfig.h')
628
629
630 def get_scheme_names():
631 """Return a tuple containing the schemes names."""
632 return tuple(sorted(_INSTALL_SCHEMES))
633
634
635 def get_path_names():
636 """Return a tuple containing the paths names."""
637 return _SCHEME_KEYS
638
639
640 def get_paths(scheme=get_default_scheme(), vars=None, expand=True):
641 """Return a mapping containing an install scheme.
642
643 ``scheme`` is the install scheme name. If not provided, it will
644 return the default scheme for the current platform.
645 """
646 if expand:
647 return _expand_vars(scheme, vars)
648 else:
649 return _INSTALL_SCHEMES[scheme]
650
651
652 def get_path(name, scheme=get_default_scheme(), vars=None, expand=True):
653 """Return a path corresponding to the scheme.
654
655 ``scheme`` is the install scheme name.
656 """
657 return get_paths(scheme, vars, expand)[name]
658
659
660 def get_config_vars(*args):
661 """With no arguments, return a dictionary of all configuration
662 variables relevant for the current platform.
663
664 On Unix, this means every variable defined in Python's installed Makefile;
665 On Windows it's a much smaller set.
666
667 With arguments, return a list of values that result from looking up
668 each argument in the configuration variable dictionary.
669 """
670 global _CONFIG_VARS
671 if _CONFIG_VARS is None:
672 _CONFIG_VARS = {}
673 # Normalized versions of prefix and exec_prefix are handy to have;
674 # in fact, these are the standard versions used most places in the
675 # Distutils.
676 _CONFIG_VARS['prefix'] = _PREFIX
677 _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
678 _CONFIG_VARS['py_version'] = _PY_VERSION
679 _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
680 _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT
681 _CONFIG_VARS['installed_base'] = _BASE_PREFIX
682 _CONFIG_VARS['base'] = _PREFIX
683 _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX
684 _CONFIG_VARS['platbase'] = _EXEC_PREFIX
685 _CONFIG_VARS['projectbase'] = _PROJECT_BASE
686 _CONFIG_VARS['platlibdir'] = sys.platlibdir
687 try:
688 _CONFIG_VARS['abiflags'] = sys.abiflags
689 except AttributeError:
690 # sys.abiflags may not be defined on all platforms.
691 _CONFIG_VARS['abiflags'] = ''
692 _CONFIG_VARS['implementation'] = _get_implementation()
693 _CONFIG_VARS['implementation_lower'] = _get_implementation().lower()
694 _CONFIG_VARS['LIBRARY'] = ''
695 try:
696 _CONFIG_VARS['py_version_nodot_plat'] = sys.winver.replace('.', '')
697 except AttributeError:
698 _CONFIG_VARS['py_version_nodot_plat'] = ''
699
700 if os.name == 'nt':
701 _init_non_posix(_CONFIG_VARS)
702 _CONFIG_VARS['VPATH'] = sys._vpath
703 if os.name == 'posix':
704 _init_posix(_CONFIG_VARS)
705 if _HAS_USER_BASE:
706 # Setting 'userbase' is done below the call to the
707 # init function to enable using 'get_config_var' in
708 # the init-function.
709 _CONFIG_VARS['userbase'] = _getuserbase()
710
711 # Always convert srcdir to an absolute path
712 srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
713 if os.name == 'posix':
714 if sys.implementation.name == 'pypy':
715 pass
716 elif _PYTHON_BUILD:
717 # If srcdir is a relative path (typically '.' or '..')
718 # then it should be interpreted relative to the directory
719 # containing Makefile.
720 base = os.path.dirname(get_makefile_filename())
721 srcdir = os.path.join(base, srcdir)
722 else:
723 # srcdir is not meaningful since the installation is
724 # spread about the filesystem. We choose the
725 # directory containing the Makefile since we know it
726 # exists.
727 srcdir = os.path.dirname(get_makefile_filename())
728 _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
729
730 # OS X platforms require special customization to handle
731 # multi-architecture, multi-os-version installers
732 if sys.platform == 'darwin':
733 import _osx_support
734 _osx_support.customize_config_vars(_CONFIG_VARS)
735
736 if args:
737 vals = []
738 for name in args:
739 vals.append(_CONFIG_VARS.get(name))
740 return vals
741 else:
742 return _CONFIG_VARS
743
744
745 def get_config_var(name):
746 """Return the value of a single variable using the dictionary returned by
747 'get_config_vars()'.
748
749 Equivalent to get_config_vars().get(name)
750 """
751 return get_config_vars().get(name)
752
753
754 def get_platform():
755 """Return a string that identifies the current platform.
756
757 This is used mainly to distinguish platform-specific build directories and
758 platform-specific built distributions. Typically includes the OS name and
759 version and the architecture (as supplied by 'os.uname()'), although the
760 exact information included depends on the OS; on Linux, the kernel version
761 isn't particularly important.
762
763 Examples of returned values:
764 linux-i586
765 linux-alpha (?)
766 solaris-2.6-sun4u
767
768 Windows will return one of:
769 win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
770 win32 (all others - specifically, sys.platform is returned)
771
772 For other non-POSIX platforms, currently just returns 'sys.platform'.
773
774 """
775 if os.name == 'nt':
776 if 'amd64' in sys.version.lower():
777 return 'win-amd64'
778 if '(arm)' in sys.version.lower():
779 return 'win-arm32'
780 if '(arm64)' in sys.version.lower():
781 return 'win-arm64'
782 return sys.platform
783
784 if os.name != "posix" or not hasattr(os, 'uname'):
785 # XXX what about the architecture? NT is Intel or Alpha
786 return sys.platform
787
788 # Set for cross builds explicitly
789 if "_PYTHON_HOST_PLATFORM" in os.environ:
790 return os.environ["_PYTHON_HOST_PLATFORM"]
791
792 # Try to distinguish various flavours of Unix
793 osname, host, release, version, machine = os.uname()
794
795 # Convert the OS name to lowercase, remove '/' characters, and translate
796 # spaces (for "Power Macintosh")
797 osname = osname.lower().replace('/', '')
798 machine = machine.replace(' ', '_')
799 machine = machine.replace('/', '-')
800
801 if osname[:5] == "linux":
802 # At least on Linux/Intel, 'machine' is the processor --
803 # i386, etc.
804 # XXX what about Alpha, SPARC, etc?
805 return f"{osname}-{machine}"
806 elif osname[:5] == "sunos":
807 if release[0] >= "5": # SunOS 5 == Solaris 2
808 osname = "solaris"
809 release = f"{int(release[0]) - 3}.{release[2:]}"
810 # We can't use "platform.architecture()[0]" because a
811 # bootstrap problem. We use a dict to get an error
812 # if some suspicious happens.
813 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
814 machine += f".{bitness[sys.maxsize]}"
815 # fall through to standard osname-release-machine representation
816 elif osname[:3] == "aix":
817 from _aix_support import aix_platform
818 return aix_platform()
819 elif osname[:6] == "cygwin":
820 osname = "cygwin"
821 import re
822 rel_re = re.compile(r'[\d.]+')
823 m = rel_re.match(release)
824 if m:
825 release = m.group()
826 elif osname[:6] == "darwin":
827 import _osx_support
828 osname, release, machine = _osx_support.get_platform_osx(
829 get_config_vars(),
830 osname, release, machine)
831
832 return f"{osname}-{release}-{machine}"
833
834
835 def get_python_version():
836 return _PY_VERSION_SHORT
837
838
839 def expand_makefile_vars(s, vars):
840 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
841 'string' according to 'vars' (a dictionary mapping variable names to
842 values). Variables not present in 'vars' are silently expanded to the
843 empty string. The variable values in 'vars' should not contain further
844 variable expansions; if 'vars' is the output of 'parse_makefile()',
845 you're fine. Returns a variable-expanded version of 's'.
846 """
847 import re
848
849 # This algorithm does multiple expansion, so if vars['foo'] contains
850 # "${bar}", it will expand ${foo} to ${bar}, and then expand
851 # ${bar}... and so forth. This is fine as long as 'vars' comes from
852 # 'parse_makefile()', which takes care of such expansions eagerly,
853 # according to make's variable expansion semantics.
854
855 while True:
856 m = re.search(_findvar1_rx, s) or re.search(_findvar2_rx, s)
857 if m:
858 (beg, end) = m.span()
859 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
860 else:
861 break
862 return s
863
864
865 def _print_dict(title, data):
866 for index, (key, value) in enumerate(sorted(data.items())):
867 if index == 0:
868 print(f'{title}: ')
869 print(f'\t{key} = "{value}"')
870
871
872 def _main():
873 """Display all information sysconfig detains."""
874 if '--generate-posix-vars' in sys.argv:
875 _generate_posix_vars(sys.argv[2:])
876 return
877 print(f'Platform: "{get_platform()}"')
878 print(f'Python version: "{get_python_version()}"')
879 print(f'Current installation scheme: "{get_default_scheme()}"')
880 print()
881 _print_dict('Paths', get_paths())
882 print()
883 _print_dict('Variables', get_config_vars())
884
885
886 if __name__ == '__main__':
887 _main()