Debian Codegraph @

lib-python/3/sysconfig.py

raw symbols ◀ ▶ SCIP
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 platform = multiarch or sys.platform
503 return os.environ.get(
504 '_PYTHON_SYSCONFIGDATA_NAME',
•505 f'_sysconfigdata_{sys.abiflags}_{platform}',
506 )
507
508
509 def _generate_posix_vars(args):
510 """Generate the Python module containing build-time variables."""
511 import pprint
512 vars = {}
513 if sys.implementation.name == 'pypy':
514 import _sysconfigdata
515 vars = _sysconfigdata.build_time_vars
516 else:
517 # load the installed Makefile:
518 makefile = get_makefile_filename()
519 try:
520 _parse_makefile(makefile, vars)
521 except OSError as e:
522 msg = f"invalid Python installation: unable to open {makefile}"
523 if hasattr(e, "strerror"):
524 msg = f"{msg} ({e.strerror})"
525 raise OSError(msg)
526 # load the installed pyconfig.h:
527 config_h = get_config_h_filename()
528 try:
529 with open(config_h, encoding="utf-8") as f:
530 parse_config_h(f, vars)
531 except OSError as e:
532 msg = f"invalid Python installation: unable to open {config_h}"
533 if hasattr(e, "strerror"):
534 msg = f"{msg} ({e.strerror})"
535 raise OSError(msg)
536 # On AIX, there are wrong paths to the linker scripts in the Makefile
537 # -- these paths are relative to the Python source, but when installed
538 # the scripts are in another directory.
539 if _PYTHON_BUILD:
540 vars['BLDSHARED'] = vars['LDSHARED']
541
542 if args:
543 # PyPy extension: they should be key, value pairs
544 for k, v in zip(args[::2], args[1::2]):
545 vars[k] = v
546 # There's a chicken-and-egg situation on OS X with regards to the
547 # _sysconfigdata module after the changes introduced by #15298:
548 # get_config_vars() is called by get_platform() as part of the
549 # `make pybuilddir.txt` target -- which is a precursor to the
550 # _sysconfigdata.py module being constructed. Unfortunately,
551 # get_config_vars() eventually calls _init_posix(), which attempts
552 # to import _sysconfigdata, which we won't have built yet. In order
553 # for _init_posix() to work, if we're on Darwin, just mock up the
554 # _sysconfigdata module manually and populate it with the build vars.
555 # This is more than sufficient for ensuring the subsequent call to
556 # get_platform() succeeds.
557 name = _get_sysconfigdata_name()
558 if 'darwin' in sys.platform:
559 import types
560 module = types.ModuleType(name)
561 module.build_time_vars = vars
562 sys.modules[name] = module
563
564 pybuilddir = f'build/lib.{get_platform()}-{_PY_VERSION_SHORT}'
565 if hasattr(sys, "gettotalrefcount"):
566 pybuilddir += '-pydebug'
567 os.makedirs(pybuilddir, exist_ok=True)
568 destfile = os.path.join(pybuilddir, name + '.py')
569
570 with open(destfile, 'w', encoding='utf8') as f:
571 f.write('# system configuration generated and used by'
572 ' the sysconfig module\n')
573 f.write('build_time_vars = ')
574 pprint.pprint(vars, stream=f)
575
576 # Create file used for sys.path fixup -- see Modules/getpath.c
577 with open('pybuilddir.txt', 'w', encoding='utf8') as f:
578 f.write(pybuilddir)
579
580 def _init_posix(vars):
581 """Initialize the module as appropriate for POSIX systems."""
582 # CPython: _sysconfigdata_* is generated at build time, see _generate_posix_vars()
583 # name = _get_sysconfigdata_name()
584 # PyPy: _sysconfigdata is a dynamic module (uses sys to determine values),
585 # while _sysconfigdata_* is a static version of the same values
586 # generated by calling _generate_posix_vars as part of packaging.py.
587 # To prevent chicken-and-egg problems of needing the values before
588 # generating them, fall back to the dynamic version here.
589 name = _get_sysconfigdata_name()
590 try:
591 _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
592 except ImportError:
593 if '_PYTHON_SYSCONFIGDATA_NAME' in os.environ:
594 raise
595 _temp = __import__("_sysconfigdata", globals(), locals(), ['build_time_vars'], 0)
596
597 build_time_vars = _temp.build_time_vars
598 vars.update(build_time_vars)
599
600 def _init_non_posix(vars):
601 """Initialize the module as appropriate for NT"""
602 # set basic install directories
603 import _imp
604 vars['LIBDEST'] = get_path('stdlib')
605 vars['BINLIBDEST'] = get_path('platstdlib')
606 vars['INCLUDEPY'] = get_path('include')
607 vars['EXT_SUFFIX'] = _imp.extension_suffixes()[0]
608 vars['EXE'] = '.exe'
609 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
610 vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
611 vars['TZPATH'] = ''
612 # pypy: give us control over the ABI tag in a wheel name
613 so_ext = _imp.extension_suffixes()[0]
614 vars['SOABI']= '-'.join(so_ext.split('.')[1].split('-')[:2])
615
616 #
617 # public APIs
618 #
619
620
621 def parse_config_h(fp, vars=None):
622 """Parse a config.h-style file.
623
624 A dictionary containing name/value pairs is returned. If an
625 optional dictionary is passed in as the second argument, it is
626 used instead of a new dictionary.
627 """
628 if vars is None:
629 vars = {}
630 import re
631 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
632 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
633
634 while True:
635 line = fp.readline()
636 if not line:
637 break
638 m = define_rx.match(line)
639 if m:
640 n, v = m.group(1, 2)
641 try:
642 if n in _ALWAYS_STR:
643 raise ValueError
644 v = int(v)
645 except ValueError:
646 pass
647 vars[n] = v
648 else:
649 m = undef_rx.match(line)
650 if m:
651 vars[m.group(1)] = 0
652 return vars
653
654
655 def get_config_h_filename():
656 """Return the path of pyconfig.h."""
657 if _PYTHON_BUILD:
658 if os.name == "nt":
659 inc_dir = os.path.join(_PROJECT_BASE, "PC")
660 else:
661 inc_dir = _PROJECT_BASE
662 else:
•663 inc_dir = get_path('platinclude', 'posix_prefix')
664 return os.path.join(inc_dir, 'pyconfig.h')
665
666
667 def get_scheme_names():
668 """Return a tuple containing the schemes names."""
669 return tuple(sorted(_INSTALL_SCHEMES))
670
671
672 def get_path_names():
673 """Return a tuple containing the paths names."""
674 return _SCHEME_KEYS
675
676
677 def get_paths(scheme=get_default_scheme(), vars=None, expand=True):
678 """Return a mapping containing an install scheme.
679
680 ``scheme`` is the install scheme name. If not provided, it will
681 return the default scheme for the current platform.
682 """
683 if expand:
684 return _expand_vars(scheme, vars)
685 else:
686 return _INSTALL_SCHEMES[scheme]
687
688
689 def get_path(name, scheme=get_default_scheme(), vars=None, expand=True):
690 """Return a path corresponding to the scheme.
691
692 ``scheme`` is the install scheme name.
693 """
694 return get_paths(scheme, vars, expand)[name]
695
696
697 def get_config_vars(*args):
698 """With no arguments, return a dictionary of all configuration
699 variables relevant for the current platform.
700
701 On Unix, this means every variable defined in Python's installed Makefile;
702 On Windows it's a much smaller set.
703
704 With arguments, return a list of values that result from looking up
705 each argument in the configuration variable dictionary.
706 """
707 global _CONFIG_VARS
708 if _CONFIG_VARS is None:
709 _CONFIG_VARS = {}
710 # Normalized versions of prefix and exec_prefix are handy to have;
711 # in fact, these are the standard versions used most places in the
712 # Distutils.
713 _CONFIG_VARS['prefix'] = _PREFIX
714 _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
715 _CONFIG_VARS['py_version'] = _PY_VERSION
716 _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
717 _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT
718 _CONFIG_VARS['installed_base'] = _BASE_PREFIX
719 _CONFIG_VARS['base'] = _PREFIX
720 _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX
721 _CONFIG_VARS['platbase'] = _EXEC_PREFIX
722 _CONFIG_VARS['projectbase'] = _PROJECT_BASE
723 _CONFIG_VARS['platlibdir'] = sys.platlibdir
724 try:
725 _CONFIG_VARS['abiflags'] = sys.abiflags
726 except AttributeError:
727 # sys.abiflags may not be defined on all platforms.
728 _CONFIG_VARS['abiflags'] = ''
729 _CONFIG_VARS['implementation'] = _get_implementation()
730 _CONFIG_VARS['implementation_lower'] = _get_implementation().lower()
731 _CONFIG_VARS['LIBRARY'] = ''
732 try:
733 _CONFIG_VARS['py_version_nodot_plat'] = sys.winver.replace('.', '')
734 except AttributeError:
735 _CONFIG_VARS['py_version_nodot_plat'] = ''
736
737 if os.name == 'nt':
738 _init_non_posix(_CONFIG_VARS)
739 _CONFIG_VARS['VPATH'] = sys._vpath
740 if os.name == 'posix':
741 _init_posix(_CONFIG_VARS)
742 if _HAS_USER_BASE:
743 # Setting 'userbase' is done below the call to the
744 # init function to enable using 'get_config_var' in
745 # the init-function.
746 _CONFIG_VARS['userbase'] = _getuserbase()
747
748 # Always convert srcdir to an absolute path
749 srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
750 if os.name == 'posix':
751 if sys.implementation.name == 'pypy':
752 pass
753 elif _PYTHON_BUILD:
754 # If srcdir is a relative path (typically '.' or '..')
755 # then it should be interpreted relative to the directory
756 # containing Makefile.
757 base = os.path.dirname(get_makefile_filename())
758 srcdir = os.path.join(base, srcdir)
759 else:
760 # srcdir is not meaningful since the installation is
761 # spread about the filesystem. We choose the
762 # directory containing the Makefile since we know it
763 # exists.
764 srcdir = os.path.dirname(get_makefile_filename())
765 _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
766
767 # OS X platforms require special customization to handle
768 # multi-architecture, multi-os-version installers
769 if sys.platform == 'darwin':
770 import _osx_support
771 _osx_support.customize_config_vars(_CONFIG_VARS)
772
773 if args:
774 vals = []
775 for name in args:
776 vals.append(_CONFIG_VARS.get(name))
777 return vals
778 else:
779 return _CONFIG_VARS
780
781
782 def get_config_var(name):
783 """Return the value of a single variable using the dictionary returned by
784 'get_config_vars()'.
785
786 Equivalent to get_config_vars().get(name)
787 """
788 return get_config_vars().get(name)
789
790
791 def get_platform():
792 """Return a string that identifies the current platform.
793
794 This is used mainly to distinguish platform-specific build directories and
795 platform-specific built distributions. Typically includes the OS name and
796 version and the architecture (as supplied by 'os.uname()'), although the
797 exact information included depends on the OS; on Linux, the kernel version
798 isn't particularly important.
799
800 Examples of returned values:
801 linux-i586
802 linux-alpha (?)
803 solaris-2.6-sun4u
804
805 Windows will return one of:
806 win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
807 win32 (all others - specifically, sys.platform is returned)
808
809 For other non-POSIX platforms, currently just returns 'sys.platform'.
810
811 """
812 if os.name == 'nt':
813 if 'amd64' in sys.version.lower():
814 return 'win-amd64'
815 if '(arm)' in sys.version.lower():
816 return 'win-arm32'
817 if '(arm64)' in sys.version.lower():
818 return 'win-arm64'
819 return sys.platform
820
821 if os.name != "posix" or not hasattr(os, 'uname'):
822 # XXX what about the architecture? NT is Intel or Alpha
823 return sys.platform
824
825 # Set for cross builds explicitly
826 if "_PYTHON_HOST_PLATFORM" in os.environ:
827 return os.environ["_PYTHON_HOST_PLATFORM"]
828
829 # Try to distinguish various flavours of Unix
830 osname, host, release, version, machine = os.uname()
831
832 # Convert the OS name to lowercase, remove '/' characters, and translate
833 # spaces (for "Power Macintosh")
834 osname = osname.lower().replace('/', '')
835 machine = machine.replace(' ', '_')
836 machine = machine.replace('/', '-')
837
838 if osname[:5] == "linux":
839 # At least on Linux/Intel, 'machine' is the processor --
840 # i386, etc.
841 # XXX what about Alpha, SPARC, etc?
842 return f"{osname}-{machine}"
843 elif osname[:5] == "sunos":
844 if release[0] >= "5": # SunOS 5 == Solaris 2
845 osname = "solaris"
846 release = f"{int(release[0]) - 3}.{release[2:]}"
847 # We can't use "platform.architecture()[0]" because a
848 # bootstrap problem. We use a dict to get an error
849 # if some suspicious happens.
850 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
851 machine += f".{bitness[sys.maxsize]}"
852 # fall through to standard osname-release-machine representation
853 elif osname[:3] == "aix":
854 from _aix_support import aix_platform
855 return aix_platform()
856 elif osname[:6] == "cygwin":
857 osname = "cygwin"
858 import re
859 rel_re = re.compile(r'[\d.]+')
860 m = rel_re.match(release)
861 if m:
862 release = m.group()
863 elif osname[:6] == "darwin":
864 import _osx_support
865 osname, release, machine = _osx_support.get_platform_osx(
866 get_config_vars(),
867 osname, release, machine)
868
869 return f"{osname}-{release}-{machine}"
870
871
872 def get_python_version():
873 return _PY_VERSION_SHORT
874
875
876 def expand_makefile_vars(s, vars):
877 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
878 'string' according to 'vars' (a dictionary mapping variable names to
879 values). Variables not present in 'vars' are silently expanded to the
880 empty string. The variable values in 'vars' should not contain further
881 variable expansions; if 'vars' is the output of 'parse_makefile()',
882 you're fine. Returns a variable-expanded version of 's'.
883 """
884 import re
885
886 # This algorithm does multiple expansion, so if vars['foo'] contains
887 # "${bar}", it will expand ${foo} to ${bar}, and then expand
888 # ${bar}... and so forth. This is fine as long as 'vars' comes from
889 # 'parse_makefile()', which takes care of such expansions eagerly,
890 # according to make's variable expansion semantics.
891
892 while True:
893 m = re.search(_findvar1_rx, s) or re.search(_findvar2_rx, s)
894 if m:
895 (beg, end) = m.span()
896 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
897 else:
898 break
899 return s
900
901
902 def _print_dict(title, data):
903 for index, (key, value) in enumerate(sorted(data.items())):
904 if index == 0:
905 print(f'{title}: ')
906 print(f'\t{key} = "{value}"')
907
908
909 def _main():
910 """Display all information sysconfig detains."""
911 if '--generate-posix-vars' in sys.argv:
912 _generate_posix_vars(sys.argv[2:])
913 return
914 print(f'Platform: "{get_platform()}"')
915 print(f'Python version: "{get_python_version()}"')
916 print(f'Current installation scheme: "{get_default_scheme()}"')
917 print()
918 _print_dict('Paths', get_paths())
919 print()
920 _print_dict('Variables', get_config_vars())
921
922
923 if __name__ == '__main__':
924 _main()