Debian Codegraph @

lib-python/3/sysconfig.py

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