ยปCore Development>Code coverage>Lib/sysconfig.py

Python code coverage for Lib/sysconfig.py

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