blob: bf04ac541e6b027f3be0a96f874088c3ea6626f7 [file] [log] [blame]
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001"""Access to Python's configuration information."""
2
3import os
4import sys
5from 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_INSTALL_SCHEMES = {
22 'posix_prefix': {
23 'stdlib': '{installed_base}/{platlibdir}/python{py_version_short}',
24 'platstdlib': '{platbase}/{platlibdir}/python{py_version_short}',
25 'purelib': '{base}/lib/python{py_version_short}/site-packages',
26 'platlib': '{platbase}/{platlibdir}/python{py_version_short}/site-packages',
27 'include':
28 '{installed_base}/include/python{py_version_short}{abiflags}',
29 'platinclude':
30 '{installed_platbase}/include/python{py_version_short}{abiflags}',
31 'scripts': '{base}/bin',
32 'data': '{base}',
33 },
34 'posix_home': {
35 'stdlib': '{installed_base}/lib/python',
36 'platstdlib': '{base}/lib/python',
37 'purelib': '{base}/lib/python',
38 'platlib': '{base}/lib/python',
39 'include': '{installed_base}/include/python',
40 'platinclude': '{installed_base}/include/python',
41 'scripts': '{base}/bin',
42 'data': '{base}',
43 },
44 'nt': {
45 'stdlib': '{installed_base}/Lib',
46 'platstdlib': '{base}/Lib',
47 'purelib': '{base}/Lib/site-packages',
48 'platlib': '{base}/Lib/site-packages',
49 'include': '{installed_base}/Include',
50 'platinclude': '{installed_base}/Include',
51 'scripts': '{base}/Scripts',
52 'data': '{base}',
53 },
54 # NOTE: When modifying "purelib" scheme, update site._get_path() too.
55 'nt_user': {
56 'stdlib': '{userbase}/Python{py_version_nodot}',
57 'platstdlib': '{userbase}/Python{py_version_nodot}',
58 'purelib': '{userbase}/Python{py_version_nodot}/site-packages',
59 'platlib': '{userbase}/Python{py_version_nodot}/site-packages',
60 'include': '{userbase}/Python{py_version_nodot}/Include',
61 'scripts': '{userbase}/Python{py_version_nodot}/Scripts',
62 'data': '{userbase}',
63 },
64 'posix_user': {
65 'stdlib': '{userbase}/{platlibdir}/python{py_version_short}',
66 'platstdlib': '{userbase}/{platlibdir}/python{py_version_short}',
67 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
68 'platlib': '{userbase}/{platlibdir}/python{py_version_short}/site-packages',
69 'include': '{userbase}/include/python{py_version_short}',
70 'scripts': '{userbase}/bin',
71 'data': '{userbase}',
72 },
73 'osx_framework_user': {
74 'stdlib': '{userbase}/lib/python',
75 'platstdlib': '{userbase}/lib/python',
76 'purelib': '{userbase}/lib/python/site-packages',
77 'platlib': '{userbase}/lib/python/site-packages',
78 'include': '{userbase}/include',
79 'scripts': '{userbase}/bin',
80 'data': '{userbase}',
81 },
82 }
83
84_SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
85 'scripts', 'data')
86
87_PY_VERSION = sys.version.split()[0]
88_PY_VERSION_SHORT = '%d.%d' % sys.version_info[:2]
89_PY_VERSION_SHORT_NO_DOT = '%d%d' % sys.version_info[:2]
90_PREFIX = os.path.normpath(sys.prefix)
91_BASE_PREFIX = os.path.normpath(sys.base_prefix)
92_EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
93_BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
94_CONFIG_VARS = None
95_USER_BASE = None
96
97
98def _safe_realpath(path):
99 try:
100 return realpath(path)
101 except OSError:
102 return path
103
104if sys.executable:
105 _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
106else:
107 # sys.executable can be empty if argv[0] has been changed and Python is
108 # unable to retrieve the real program name
109 _PROJECT_BASE = _safe_realpath(os.getcwd())
110
111if (os.name == 'nt' and
112 _PROJECT_BASE.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
113 _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir))
114
115# set for cross builds
116if "_PYTHON_PROJECT_BASE" in os.environ:
117 _PROJECT_BASE = _safe_realpath(os.environ["_PYTHON_PROJECT_BASE"])
118
119def _is_python_source_dir(d):
120 for fn in ("Setup", "Setup.local"):
121 if os.path.isfile(os.path.join(d, "Modules", fn)):
122 return True
123 return False
124
125_sys_home = getattr(sys, '_home', None)
126
127if os.name == 'nt':
128 def _fix_pcbuild(d):
129 if d and os.path.normcase(d).startswith(
130 os.path.normcase(os.path.join(_PREFIX, "PCbuild"))):
131 return _PREFIX
132 return d
133 _PROJECT_BASE = _fix_pcbuild(_PROJECT_BASE)
134 _sys_home = _fix_pcbuild(_sys_home)
135
136def is_python_build(check_home=False):
137 if check_home and _sys_home:
138 return _is_python_source_dir(_sys_home)
139 return _is_python_source_dir(_PROJECT_BASE)
140
141_PYTHON_BUILD = is_python_build(True)
142
143if _PYTHON_BUILD:
144 for scheme in ('posix_prefix', 'posix_home'):
145 _INSTALL_SCHEMES[scheme]['include'] = '{srcdir}/Include'
146 _INSTALL_SCHEMES[scheme]['platinclude'] = '{projectbase}/.'
147
148
149def _subst_vars(s, local_vars):
150 try:
151 return s.format(**local_vars)
152 except KeyError:
153 try:
154 return s.format(**os.environ)
155 except KeyError as var:
156 raise AttributeError('{%s}' % var) from None
157
158def _extend_dict(target_dict, other_dict):
159 target_keys = target_dict.keys()
160 for key, value in other_dict.items():
161 if key in target_keys:
162 continue
163 target_dict[key] = value
164
165
166def _expand_vars(scheme, vars):
167 res = {}
168 if vars is None:
169 vars = {}
170 _extend_dict(vars, get_config_vars())
171
172 for key, value in _INSTALL_SCHEMES[scheme].items():
173 if os.name in ('posix', 'nt'):
174 value = os.path.expanduser(value)
175 res[key] = os.path.normpath(_subst_vars(value, vars))
176 return res
177
178
179def _get_default_scheme():
180 if os.name == 'posix':
181 # the default scheme for posix is posix_prefix
182 return 'posix_prefix'
183 return os.name
184
185
186# NOTE: site.py has copy of this function.
187# Sync it when modify this function.
188def _getuserbase():
189 env_base = os.environ.get("PYTHONUSERBASE", None)
190 if env_base:
191 return env_base
192
193 def joinuser(*args):
194 return os.path.expanduser(os.path.join(*args))
195
196 if os.name == "nt":
197 base = os.environ.get("APPDATA") or "~"
198 return joinuser(base, "Python")
199
200 if sys.platform == "darwin" and sys._framework:
201 return joinuser("~", "Library", sys._framework,
202 "%d.%d" % sys.version_info[:2])
203
204 return joinuser("~", ".local")
205
206
207def _parse_makefile(filename, vars=None):
208 """Parse a Makefile-style file.
209
210 A dictionary containing name/value pairs is returned. If an
211 optional dictionary is passed in as the second argument, it is
212 used instead of a new dictionary.
213 """
214 # Regexes needed for parsing Makefile (and similar syntaxes,
215 # like old-style Setup files).
216 import re
217 _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
218 _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
219 _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
220
221 if vars is None:
222 vars = {}
223 done = {}
224 notdone = {}
225
226 with open(filename, errors="surrogateescape") as f:
227 lines = f.readlines()
228
229 for line in lines:
230 if line.startswith('#') or line.strip() == '':
231 continue
232 m = _variable_rx.match(line)
233 if m:
234 n, v = m.group(1, 2)
235 v = v.strip()
236 # `$$' is a literal `$' in make
237 tmpv = v.replace('$$', '')
238
239 if "$" in tmpv:
240 notdone[n] = v
241 else:
242 try:
243 v = int(v)
244 except ValueError:
245 # insert literal `$'
246 done[n] = v.replace('$$', '$')
247 else:
248 done[n] = v
249
250 # do variable interpolation here
251 variables = list(notdone.keys())
252
253 # Variables with a 'PY_' prefix in the makefile. These need to
254 # be made available without that prefix through sysconfig.
255 # Special care is needed to ensure that variable expansion works, even
256 # if the expansion uses the name without a prefix.
257 renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
258
259 while len(variables) > 0:
260 for name in tuple(variables):
261 value = notdone[name]
262 m1 = _findvar1_rx.search(value)
263 m2 = _findvar2_rx.search(value)
264 if m1 and m2:
265 m = m1 if m1.start() < m2.start() else m2
266 else:
267 m = m1 if m1 else m2
268 if m is not None:
269 n = m.group(1)
270 found = True
271 if n in done:
272 item = str(done[n])
273 elif n in notdone:
274 # get it on a subsequent round
275 found = False
276 elif n in os.environ:
277 # do it like make: fall back to environment
278 item = os.environ[n]
279
280 elif n in renamed_variables:
281 if (name.startswith('PY_') and
282 name[3:] in renamed_variables):
283 item = ""
284
285 elif 'PY_' + n in notdone:
286 found = False
287
288 else:
289 item = str(done['PY_' + n])
290
291 else:
292 done[n] = item = ""
293
294 if found:
295 after = value[m.end():]
296 value = value[:m.start()] + item + after
297 if "$" in after:
298 notdone[name] = value
299 else:
300 try:
301 value = int(value)
302 except ValueError:
303 done[name] = value.strip()
304 else:
305 done[name] = value
306 variables.remove(name)
307
308 if name.startswith('PY_') \
309 and name[3:] in renamed_variables:
310
311 name = name[3:]
312 if name not in done:
313 done[name] = value
314
315 else:
316 # bogus variable reference (e.g. "prefix=$/opt/python");
317 # just drop it since we can't deal
318 done[name] = value
319 variables.remove(name)
320
321 # strip spurious spaces
322 for k, v in done.items():
323 if isinstance(v, str):
324 done[k] = v.strip()
325
326 # save the results in the global dictionary
327 vars.update(done)
328 return vars
329
330
331def get_makefile_filename():
332 """Return the path of the Makefile."""
333 if _PYTHON_BUILD:
334 return os.path.join(_sys_home or _PROJECT_BASE, "Makefile")
335 if hasattr(sys, 'abiflags'):
336 config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags)
337 else:
338 config_dir_name = 'config'
339 if hasattr(sys.implementation, '_multiarch'):
340 config_dir_name += '-%s' % sys.implementation._multiarch
341 return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
342
343
344def _get_sysconfigdata_name():
345 return os.environ.get('_PYTHON_SYSCONFIGDATA_NAME',
346 '_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
347 abi=sys.abiflags,
348 platform=sys.platform,
349 multiarch=getattr(sys.implementation, '_multiarch', ''),
350 ))
351
352
353def _generate_posix_vars():
354 """Generate the Python module containing build-time variables."""
355 import pprint
356 vars = {}
357 # load the installed Makefile:
358 makefile = get_makefile_filename()
359 try:
360 _parse_makefile(makefile, vars)
361 except OSError as e:
362 msg = "invalid Python installation: unable to open %s" % makefile
363 if hasattr(e, "strerror"):
364 msg = msg + " (%s)" % e.strerror
365 raise OSError(msg)
366 # load the installed pyconfig.h:
367 config_h = get_config_h_filename()
368 try:
369 with open(config_h) as f:
370 parse_config_h(f, vars)
371 except OSError as e:
372 msg = "invalid Python installation: unable to open %s" % config_h
373 if hasattr(e, "strerror"):
374 msg = msg + " (%s)" % e.strerror
375 raise OSError(msg)
376 # On AIX, there are wrong paths to the linker scripts in the Makefile
377 # -- these paths are relative to the Python source, but when installed
378 # the scripts are in another directory.
379 if _PYTHON_BUILD:
380 vars['BLDSHARED'] = vars['LDSHARED']
381
382 # There's a chicken-and-egg situation on OS X with regards to the
383 # _sysconfigdata module after the changes introduced by #15298:
384 # get_config_vars() is called by get_platform() as part of the
385 # `make pybuilddir.txt` target -- which is a precursor to the
386 # _sysconfigdata.py module being constructed. Unfortunately,
387 # get_config_vars() eventually calls _init_posix(), which attempts
388 # to import _sysconfigdata, which we won't have built yet. In order
389 # for _init_posix() to work, if we're on Darwin, just mock up the
390 # _sysconfigdata module manually and populate it with the build vars.
391 # This is more than sufficient for ensuring the subsequent call to
392 # get_platform() succeeds.
393 name = _get_sysconfigdata_name()
394 if 'darwin' in sys.platform:
395 import types
396 module = types.ModuleType(name)
397 module.build_time_vars = vars
398 sys.modules[name] = module
399
400 pybuilddir = 'build/lib.%s-%s' % (get_platform(), _PY_VERSION_SHORT)
401 if hasattr(sys, "gettotalrefcount"):
402 pybuilddir += '-pydebug'
403 os.makedirs(pybuilddir, exist_ok=True)
404 destfile = os.path.join(pybuilddir, name + '.py')
405
406 with open(destfile, 'w', encoding='utf8') as f:
407 f.write('# system configuration generated and used by'
408 ' the sysconfig module\n')
409 f.write('build_time_vars = ')
410 pprint.pprint(vars, stream=f)
411
412 # Create file used for sys.path fixup -- see Modules/getpath.c
413 with open('pybuilddir.txt', 'w', encoding='utf8') as f:
414 f.write(pybuilddir)
415
416def _init_posix(vars):
417 """Initialize the module as appropriate for POSIX systems."""
418 # _sysconfigdata is generated at build time, see _generate_posix_vars()
419 name = _get_sysconfigdata_name()
420 _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
421 build_time_vars = _temp.build_time_vars
422 vars.update(build_time_vars)
423
424def _init_non_posix(vars):
425 """Initialize the module as appropriate for NT"""
426 # set basic install directories
427 vars['LIBDEST'] = get_path('stdlib')
428 vars['BINLIBDEST'] = get_path('platstdlib')
429 vars['INCLUDEPY'] = get_path('include')
430 vars['EXT_SUFFIX'] = '.pyd'
431 vars['EXE'] = '.exe'
432 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
433 vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
434
435#
436# public APIs
437#
438
439
440def parse_config_h(fp, vars=None):
441 """Parse a config.h-style file.
442
443 A dictionary containing name/value pairs is returned. If an
444 optional dictionary is passed in as the second argument, it is
445 used instead of a new dictionary.
446 """
447 if vars is None:
448 vars = {}
449 import re
450 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
451 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
452
453 while True:
454 line = fp.readline()
455 if not line:
456 break
457 m = define_rx.match(line)
458 if m:
459 n, v = m.group(1, 2)
460 try:
461 v = int(v)
462 except ValueError:
463 pass
464 vars[n] = v
465 else:
466 m = undef_rx.match(line)
467 if m:
468 vars[m.group(1)] = 0
469 return vars
470
471
472def get_config_h_filename():
473 """Return the path of pyconfig.h."""
474 if _PYTHON_BUILD:
475 if os.name == "nt":
476 inc_dir = os.path.join(_sys_home or _PROJECT_BASE, "PC")
477 else:
478 inc_dir = _sys_home or _PROJECT_BASE
479 else:
480 inc_dir = get_path('platinclude')
481 return os.path.join(inc_dir, 'pyconfig.h')
482
483
484def get_scheme_names():
485 """Return a tuple containing the schemes names."""
486 return tuple(sorted(_INSTALL_SCHEMES))
487
488
489def get_path_names():
490 """Return a tuple containing the paths names."""
491 return _SCHEME_KEYS
492
493
494def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
495 """Return a mapping containing an install scheme.
496
497 ``scheme`` is the install scheme name. If not provided, it will
498 return the default scheme for the current platform.
499 """
500 if expand:
501 return _expand_vars(scheme, vars)
502 else:
503 return _INSTALL_SCHEMES[scheme]
504
505
506def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
507 """Return a path corresponding to the scheme.
508
509 ``scheme`` is the install scheme name.
510 """
511 return get_paths(scheme, vars, expand)[name]
512
513
514def get_config_vars(*args):
515 """With no arguments, return a dictionary of all configuration
516 variables relevant for the current platform.
517
518 On Unix, this means every variable defined in Python's installed Makefile;
519 On Windows it's a much smaller set.
520
521 With arguments, return a list of values that result from looking up
522 each argument in the configuration variable dictionary.
523 """
524 global _CONFIG_VARS
525 if _CONFIG_VARS is None:
526 _CONFIG_VARS = {}
527 # Normalized versions of prefix and exec_prefix are handy to have;
528 # in fact, these are the standard versions used most places in the
529 # Distutils.
530 _CONFIG_VARS['prefix'] = _PREFIX
531 _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
532 _CONFIG_VARS['py_version'] = _PY_VERSION
533 _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
534 _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT
535 _CONFIG_VARS['installed_base'] = _BASE_PREFIX
536 _CONFIG_VARS['base'] = _PREFIX
537 _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX
538 _CONFIG_VARS['platbase'] = _EXEC_PREFIX
539 _CONFIG_VARS['projectbase'] = _PROJECT_BASE
540 _CONFIG_VARS['platlibdir'] = sys.platlibdir
541 try:
542 _CONFIG_VARS['abiflags'] = sys.abiflags
543 except AttributeError:
544 # sys.abiflags may not be defined on all platforms.
545 _CONFIG_VARS['abiflags'] = ''
546
547 if os.name == 'nt':
548 _init_non_posix(_CONFIG_VARS)
549 _CONFIG_VARS['TZPATH'] = ''
550 if os.name == 'posix':
551 _init_posix(_CONFIG_VARS)
552 # For backward compatibility, see issue19555
553 SO = _CONFIG_VARS.get('EXT_SUFFIX')
554 if SO is not None:
555 _CONFIG_VARS['SO'] = SO
556 # Setting 'userbase' is done below the call to the
557 # init function to enable using 'get_config_var' in
558 # the init-function.
559 _CONFIG_VARS['userbase'] = _getuserbase()
560
561 # Always convert srcdir to an absolute path
562 srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
563 if os.name == 'posix':
564 if _PYTHON_BUILD:
565 # If srcdir is a relative path (typically '.' or '..')
566 # then it should be interpreted relative to the directory
567 # containing Makefile.
568 base = os.path.dirname(get_makefile_filename())
569 srcdir = os.path.join(base, srcdir)
570 else:
571 # srcdir is not meaningful since the installation is
572 # spread about the filesystem. We choose the
573 # directory containing the Makefile since we know it
574 # exists.
575 srcdir = os.path.dirname(get_makefile_filename())
576 _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
577
578 # OS X platforms require special customization to handle
579 # multi-architecture, multi-os-version installers
580 if sys.platform == 'darwin':
581 import _osx_support
582 _osx_support.customize_config_vars(_CONFIG_VARS)
583
584 if args:
585 vals = []
586 for name in args:
587 vals.append(_CONFIG_VARS.get(name))
588 return vals
589 else:
590 return _CONFIG_VARS
591
592
593def get_config_var(name):
594 """Return the value of a single variable using the dictionary returned by
595 'get_config_vars()'.
596
597 Equivalent to get_config_vars().get(name)
598 """
599 if name == 'SO':
600 import warnings
601 warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
602 return get_config_vars().get(name)
603
604
605def get_platform():
606 """Return a string that identifies the current platform.
607
608 This is used mainly to distinguish platform-specific build directories and
609 platform-specific built distributions. Typically includes the OS name and
610 version and the architecture (as supplied by 'os.uname()'), although the
611 exact information included depends on the OS; on Linux, the kernel version
612 isn't particularly important.
613
614 Examples of returned values:
615 linux-i586
616 linux-alpha (?)
617 solaris-2.6-sun4u
618
619 Windows will return one of:
620 win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
621 win32 (all others - specifically, sys.platform is returned)
622
623 For other non-POSIX platforms, currently just returns 'sys.platform'.
624
625 """
626 if os.name == 'nt':
627 if 'amd64' in sys.version.lower():
628 return 'win-amd64'
629 if '(arm)' in sys.version.lower():
630 return 'win-arm32'
631 if '(arm64)' in sys.version.lower():
632 return 'win-arm64'
633 return sys.platform
634
635 if os.name != "posix" or not hasattr(os, 'uname'):
636 # XXX what about the architecture? NT is Intel or Alpha
637 return sys.platform
638
639 # Set for cross builds explicitly
640 if "_PYTHON_HOST_PLATFORM" in os.environ:
641 return os.environ["_PYTHON_HOST_PLATFORM"]
642
643 # Try to distinguish various flavours of Unix
644 osname, host, release, version, machine = os.uname()
645
646 # Convert the OS name to lowercase, remove '/' characters, and translate
647 # spaces (for "Power Macintosh")
648 osname = osname.lower().replace('/', '')
649 machine = machine.replace(' ', '_')
650 machine = machine.replace('/', '-')
651
652 if osname[:5] == "linux":
653 # At least on Linux/Intel, 'machine' is the processor --
654 # i386, etc.
655 # XXX what about Alpha, SPARC, etc?
656 return "%s-%s" % (osname, machine)
657 elif osname[:5] == "sunos":
658 if release[0] >= "5": # SunOS 5 == Solaris 2
659 osname = "solaris"
660 release = "%d.%s" % (int(release[0]) - 3, release[2:])
661 # We can't use "platform.architecture()[0]" because a
662 # bootstrap problem. We use a dict to get an error
663 # if some suspicious happens.
664 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
665 machine += ".%s" % bitness[sys.maxsize]
666 # fall through to standard osname-release-machine representation
667 elif osname[:3] == "aix":
668 from _aix_support import aix_platform
669 return aix_platform()
670 elif osname[:6] == "cygwin":
671 osname = "cygwin"
672 import re
673 rel_re = re.compile(r'[\d.]+')
674 m = rel_re.match(release)
675 if m:
676 release = m.group()
677 elif osname[:6] == "darwin":
678 import _osx_support
679 osname, release, machine = _osx_support.get_platform_osx(
680 get_config_vars(),
681 osname, release, machine)
682
683 return "%s-%s-%s" % (osname, release, machine)
684
685
686def get_python_version():
687 return _PY_VERSION_SHORT
688
689
690def _print_dict(title, data):
691 for index, (key, value) in enumerate(sorted(data.items())):
692 if index == 0:
693 print('%s: ' % (title))
694 print('\t%s = "%s"' % (key, value))
695
696
697def _main():
698 """Display all information sysconfig detains."""
699 if '--generate-posix-vars' in sys.argv:
700 _generate_posix_vars()
701 return
702 print('Platform: "%s"' % get_platform())
703 print('Python version: "%s"' % get_python_version())
704 print('Current installation scheme: "%s"' % _get_default_scheme())
705 print()
706 _print_dict('Paths', get_paths())
707 print()
708 _print_dict('Variables', get_config_vars())
709
710
711if __name__ == '__main__':
712 _main()