blob: 5b3a994af9dd7b855dbaa776773a80cbe39cd469 [file] [log] [blame]
Tarek Ziadéedacea32010-01-29 11:41:03 +00001"""Provide access to Python's configuration information.
2
3"""
4import sys
5import os
Florent Xiclunaa4707382010-03-11 00:05:17 +00006from os.path import pardir, realpath
Tarek Ziadéedacea32010-01-29 11:41:03 +00007
Barry Warsawebbef6f2010-09-20 15:29:53 +00008__all__ = [
9 'get_config_h_filename',
10 'get_config_var',
11 'get_config_vars',
12 'get_makefile_filename',
13 'get_path',
14 'get_path_names',
15 'get_paths',
16 'get_platform',
17 'get_python_version',
18 'get_scheme_names',
19 'parse_config_h',
20 ]
Tarek Ziadé16ed6cb2010-05-25 09:47:06 +000021
Tarek Ziadéedacea32010-01-29 11:41:03 +000022_INSTALL_SCHEMES = {
23 'posix_prefix': {
24 'stdlib': '{base}/lib/python{py_version_short}',
25 'platstdlib': '{platbase}/lib/python{py_version_short}',
26 'purelib': '{base}/lib/python{py_version_short}/site-packages',
27 'platlib': '{platbase}/lib/python{py_version_short}/site-packages',
Barry Warsaw14d98ac2010-11-24 19:43:47 +000028 'include':
29 '{base}/include/python{py_version_short}{abiflags}',
30 'platinclude':
31 '{platbase}/include/python{py_version_short}{abiflags}',
Tarek Ziadéedacea32010-01-29 11:41:03 +000032 'scripts': '{base}/bin',
33 'data': '{base}',
34 },
35 'posix_home': {
36 'stdlib': '{base}/lib/python',
37 'platstdlib': '{base}/lib/python',
38 'purelib': '{base}/lib/python',
39 'platlib': '{base}/lib/python',
40 'include': '{base}/include/python',
41 'platinclude': '{base}/include/python',
42 'scripts': '{base}/bin',
43 'data' : '{base}',
44 },
45 'nt': {
46 'stdlib': '{base}/Lib',
47 'platstdlib': '{base}/Lib',
48 'purelib': '{base}/Lib/site-packages',
49 'platlib': '{base}/Lib/site-packages',
50 'include': '{base}/Include',
51 'platinclude': '{base}/Include',
52 'scripts': '{base}/Scripts',
53 'data' : '{base}',
54 },
55 'os2': {
56 'stdlib': '{base}/Lib',
57 'platstdlib': '{base}/Lib',
58 'purelib': '{base}/Lib/site-packages',
59 'platlib': '{base}/Lib/site-packages',
60 'include': '{base}/Include',
61 'platinclude': '{base}/Include',
62 'scripts': '{base}/Scripts',
63 'data' : '{base}',
64 },
65 'os2_home': {
Tarek Ziadé06710a82010-05-19 22:25:00 +000066 'stdlib': '{userbase}/lib/python{py_version_short}',
67 'platstdlib': '{userbase}/lib/python{py_version_short}',
68 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
69 'platlib': '{userbase}/lib/python{py_version_short}/site-packages',
Tarek Ziadéedacea32010-01-29 11:41:03 +000070 'include': '{userbase}/include/python{py_version_short}',
71 'scripts': '{userbase}/bin',
72 'data' : '{userbase}',
73 },
74 'nt_user': {
75 'stdlib': '{userbase}/Python{py_version_nodot}',
76 'platstdlib': '{userbase}/Python{py_version_nodot}',
77 'purelib': '{userbase}/Python{py_version_nodot}/site-packages',
78 'platlib': '{userbase}/Python{py_version_nodot}/site-packages',
79 'include': '{userbase}/Python{py_version_nodot}/Include',
80 'scripts': '{userbase}/Scripts',
81 'data' : '{userbase}',
82 },
83 'posix_user': {
Tarek Ziadé06710a82010-05-19 22:25:00 +000084 'stdlib': '{userbase}/lib/python{py_version_short}',
85 'platstdlib': '{userbase}/lib/python{py_version_short}',
86 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
87 'platlib': '{userbase}/lib/python{py_version_short}/site-packages',
Tarek Ziadéedacea32010-01-29 11:41:03 +000088 'include': '{userbase}/include/python{py_version_short}',
89 'scripts': '{userbase}/bin',
90 'data' : '{userbase}',
91 },
Ronald Oussoren4cda46a2010-05-08 10:49:43 +000092 'osx_framework_user': {
93 'stdlib': '{userbase}/lib/python',
94 'platstdlib': '{userbase}/lib/python',
95 'purelib': '{userbase}/lib/python/site-packages',
96 'platlib': '{userbase}/lib/python/site-packages',
97 'include': '{userbase}/include',
98 'scripts': '{userbase}/bin',
99 'data' : '{userbase}',
100 },
Tarek Ziadéedacea32010-01-29 11:41:03 +0000101 }
102
103_SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
104 'scripts', 'data')
105_PY_VERSION = sys.version.split()[0]
106_PY_VERSION_SHORT = sys.version[:3]
107_PY_VERSION_SHORT_NO_DOT = _PY_VERSION[0] + _PY_VERSION[2]
108_PREFIX = os.path.normpath(sys.prefix)
109_EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
110_CONFIG_VARS = None
111_USER_BASE = None
Victor Stinnerb103a932010-10-12 22:23:23 +0000112
113def _safe_realpath(path):
114 try:
115 return realpath(path)
116 except OSError:
117 return path
118
Victor Stinner171ba052010-03-12 14:20:59 +0000119if sys.executable:
Victor Stinnerb103a932010-10-12 22:23:23 +0000120 _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
Victor Stinner171ba052010-03-12 14:20:59 +0000121else:
122 # sys.executable can be empty if argv[0] has been changed and Python is
123 # unable to retrieve the real program name
Victor Stinnerb103a932010-10-12 22:23:23 +0000124 _PROJECT_BASE = _safe_realpath(os.getcwd())
Tarek Ziadéedacea32010-01-29 11:41:03 +0000125
126if os.name == "nt" and "pcbuild" in _PROJECT_BASE[-8:].lower():
Victor Stinnerb103a932010-10-12 22:23:23 +0000127 _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir))
Tarek Ziadéedacea32010-01-29 11:41:03 +0000128# PC/VS7.1
129if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower():
Victor Stinnerb103a932010-10-12 22:23:23 +0000130 _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir))
Tarek Ziadéedacea32010-01-29 11:41:03 +0000131# PC/AMD64
132if os.name == "nt" and "\\pcbuild\\amd64" in _PROJECT_BASE[-14:].lower():
Victor Stinnerb103a932010-10-12 22:23:23 +0000133 _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir))
Tarek Ziadéedacea32010-01-29 11:41:03 +0000134
135def is_python_build():
136 for fn in ("Setup.dist", "Setup.local"):
137 if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)):
138 return True
139 return False
140
141_PYTHON_BUILD = is_python_build()
142
143if _PYTHON_BUILD:
144 for scheme in ('posix_prefix', 'posix_home'):
Vinay Sajipae7d7fa2010-09-20 10:29:54 +0000145 _INSTALL_SCHEMES[scheme]['include'] = '{srcdir}/Include'
Ronald Oussorene41a19e2010-06-15 16:05:20 +0000146 _INSTALL_SCHEMES[scheme]['platinclude'] = '{projectbase}/.'
Tarek Ziadéedacea32010-01-29 11:41:03 +0000147
148def _subst_vars(s, local_vars):
149 try:
150 return s.format(**local_vars)
151 except KeyError:
152 try:
153 return s.format(**os.environ)
154 except KeyError as var:
155 raise AttributeError('{%s}' % var)
156
157def _extend_dict(target_dict, other_dict):
158 target_keys = target_dict.keys()
159 for key, value in other_dict.items():
160 if key in target_keys:
161 continue
162 target_dict[key] = value
163
164def _expand_vars(scheme, vars):
165 res = {}
166 if vars is None:
167 vars = {}
168 _extend_dict(vars, get_config_vars())
169
170 for key, value in _INSTALL_SCHEMES[scheme].items():
171 if os.name in ('posix', 'nt'):
172 value = os.path.expanduser(value)
173 res[key] = os.path.normpath(_subst_vars(value, vars))
174 return res
175
176def _get_default_scheme():
177 if os.name == 'posix':
178 # the default scheme for posix is posix_prefix
179 return 'posix_prefix'
180 return os.name
181
182def _getuserbase():
183 env_base = os.environ.get("PYTHONUSERBASE", None)
184 def joinuser(*args):
185 return os.path.expanduser(os.path.join(*args))
186
187 # what about 'os2emx', 'riscos' ?
188 if os.name == "nt":
189 base = os.environ.get("APPDATA") or "~"
190 return env_base if env_base else joinuser(base, "Python")
191
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000192 if sys.platform == "darwin":
193 framework = get_config_var("PYTHONFRAMEWORK")
194 if framework:
Ronald Oussorenbda46722010-08-01 09:02:50 +0000195 return env_base if env_base else joinuser("~", "Library", framework, "%d.%d"%(
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000196 sys.version_info[:2]))
197
Tarek Ziadéedacea32010-01-29 11:41:03 +0000198 return env_base if env_base else joinuser("~", ".local")
199
200
201def _parse_makefile(filename, vars=None):
202 """Parse a Makefile-style file.
203
204 A dictionary containing name/value pairs is returned. If an
205 optional dictionary is passed in as the second argument, it is
206 used instead of a new dictionary.
207 """
208 import re
209 # Regexes needed for parsing Makefile (and similar syntaxes,
210 # like old-style Setup files).
211 _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
212 _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
213 _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
214
215 if vars is None:
216 vars = {}
217 done = {}
218 notdone = {}
219
Victor Stinner75d8c5c2010-10-23 17:02:31 +0000220 with open(filename, errors="surrogateescape") as f:
Tarek Ziadéedacea32010-01-29 11:41:03 +0000221 lines = f.readlines()
222
223 for line in lines:
224 if line.startswith('#') or line.strip() == '':
225 continue
226 m = _variable_rx.match(line)
227 if m:
228 n, v = m.group(1, 2)
229 v = v.strip()
230 # `$$' is a literal `$' in make
231 tmpv = v.replace('$$', '')
232
233 if "$" in tmpv:
234 notdone[n] = v
235 else:
236 try:
237 v = int(v)
238 except ValueError:
239 # insert literal `$'
240 done[n] = v.replace('$$', '$')
241 else:
242 done[n] = v
243
244 # do variable interpolation here
245 variables = list(notdone.keys())
246
Ronald Oussorend21886c2010-07-20 16:07:10 +0000247 # Variables with a 'PY_' prefix in the makefile. These need to
248 # be made available without that prefix through sysconfig.
249 # Special care is needed to ensure that variable expansion works, even
250 # if the expansion uses the name without a prefix.
251 renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
252
Tarek Ziadéedacea32010-01-29 11:41:03 +0000253 while len(variables) > 0:
254 for name in tuple(variables):
255 value = notdone[name]
256 m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
257 if m is not None:
258 n = m.group(1)
259 found = True
260 if n in done:
261 item = str(done[n])
262 elif n in notdone:
263 # get it on a subsequent round
264 found = False
265 elif n in os.environ:
266 # do it like make: fall back to environment
267 item = os.environ[n]
Ronald Oussorend21886c2010-07-20 16:07:10 +0000268
269 elif n in renamed_variables:
270 if name.startswith('PY_') and name[3:] in renamed_variables:
271 item = ""
272
273 elif 'PY_' + n in notdone:
274 found = False
275
276 else:
277 item = str(done['PY_' + n])
278
Tarek Ziadéedacea32010-01-29 11:41:03 +0000279 else:
280 done[n] = item = ""
Ronald Oussorend21886c2010-07-20 16:07:10 +0000281
Tarek Ziadéedacea32010-01-29 11:41:03 +0000282 if found:
283 after = value[m.end():]
284 value = value[:m.start()] + item + after
285 if "$" in after:
286 notdone[name] = value
287 else:
288 try:
289 value = int(value)
290 except ValueError:
291 done[name] = value.strip()
292 else:
293 done[name] = value
294 variables.remove(name)
Ronald Oussorend21886c2010-07-20 16:07:10 +0000295
296 if name.startswith('PY_') \
Victor Stinner1273b7c2011-05-24 23:37:07 +0200297 and name[3:] in renamed_variables:
Ronald Oussorend21886c2010-07-20 16:07:10 +0000298
299 name = name[3:]
300 if name not in done:
301 done[name] = value
302
303
Tarek Ziadéedacea32010-01-29 11:41:03 +0000304 else:
Victor Stinner1273b7c2011-05-24 23:37:07 +0200305 # bogus variable reference (e.g. "prefix=$/opt/python");
306 # just drop it since we can't deal
307 done[name] = value
Tarek Ziadéedacea32010-01-29 11:41:03 +0000308 variables.remove(name)
309
Antoine Pitroudbec7802010-10-10 09:37:12 +0000310 # strip spurious spaces
311 for k, v in done.items():
312 if isinstance(v, str):
313 done[k] = v.strip()
314
Tarek Ziadéedacea32010-01-29 11:41:03 +0000315 # save the results in the global dictionary
316 vars.update(done)
317 return vars
318
Tarek Ziadéedacea32010-01-29 11:41:03 +0000319
Barry Warsawebbef6f2010-09-20 15:29:53 +0000320def get_makefile_filename():
Éric Araujo300623d2010-11-22 01:19:20 +0000321 """Return the path of the Makefile."""
Tarek Ziadéedacea32010-01-29 11:41:03 +0000322 if _PYTHON_BUILD:
323 return os.path.join(_PROJECT_BASE, "Makefile")
Barry Warsaw14d98ac2010-11-24 19:43:47 +0000324 return os.path.join(get_path('stdlib'),
325 'config-{}{}'.format(_PY_VERSION_SHORT, sys.abiflags),
326 'Makefile')
Tarek Ziadéedacea32010-01-29 11:41:03 +0000327
Tarek Ziadéedacea32010-01-29 11:41:03 +0000328
329def _init_posix(vars):
330 """Initialize the module as appropriate for POSIX systems."""
331 # load the installed Makefile:
Barry Warsawebbef6f2010-09-20 15:29:53 +0000332 makefile = get_makefile_filename()
Tarek Ziadéedacea32010-01-29 11:41:03 +0000333 try:
334 _parse_makefile(makefile, vars)
335 except IOError as e:
336 msg = "invalid Python installation: unable to open %s" % makefile
337 if hasattr(e, "strerror"):
338 msg = msg + " (%s)" % e.strerror
339 raise IOError(msg)
340 # load the installed pyconfig.h:
341 config_h = get_config_h_filename()
342 try:
Antoine Pitroub86680e2010-10-14 21:15:17 +0000343 with open(config_h) as f:
344 parse_config_h(f, vars)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000345 except IOError as e:
346 msg = "invalid Python installation: unable to open %s" % config_h
347 if hasattr(e, "strerror"):
348 msg = msg + " (%s)" % e.strerror
349 raise IOError(msg)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000350 # On AIX, there are wrong paths to the linker scripts in the Makefile
351 # -- these paths are relative to the Python source, but when installed
352 # the scripts are in another directory.
353 if _PYTHON_BUILD:
354 vars['LDSHARED'] = vars['BLDSHARED']
355
356def _init_non_posix(vars):
357 """Initialize the module as appropriate for NT"""
358 # set basic install directories
359 vars['LIBDEST'] = get_path('stdlib')
360 vars['BINLIBDEST'] = get_path('platstdlib')
361 vars['INCLUDEPY'] = get_path('include')
362 vars['SO'] = '.pyd'
doko@ubuntu.comd5537d02013-03-21 13:21:49 -0700363 vars['EXT_SUFFIX'] = '.pyd'
Tarek Ziadéedacea32010-01-29 11:41:03 +0000364 vars['EXE'] = '.exe'
365 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
Victor Stinnerb103a932010-10-12 22:23:23 +0000366 vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
Tarek Ziadéedacea32010-01-29 11:41:03 +0000367
368#
369# public APIs
370#
371
Tarek Ziadébd797682010-02-02 23:16:13 +0000372
373def parse_config_h(fp, vars=None):
374 """Parse a config.h-style file.
375
376 A dictionary containing name/value pairs is returned. If an
377 optional dictionary is passed in as the second argument, it is
378 used instead of a new dictionary.
379 """
380 import re
381 if vars is None:
382 vars = {}
383 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
384 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
385
386 while True:
387 line = fp.readline()
388 if not line:
389 break
390 m = define_rx.match(line)
391 if m:
392 n, v = m.group(1, 2)
393 try: v = int(v)
394 except ValueError: pass
395 vars[n] = v
396 else:
397 m = undef_rx.match(line)
398 if m:
399 vars[m.group(1)] = 0
400 return vars
401
402def get_config_h_filename():
Éric Araujo300623d2010-11-22 01:19:20 +0000403 """Return the path of pyconfig.h."""
Tarek Ziadébd797682010-02-02 23:16:13 +0000404 if _PYTHON_BUILD:
405 if os.name == "nt":
406 inc_dir = os.path.join(_PROJECT_BASE, "PC")
407 else:
408 inc_dir = _PROJECT_BASE
409 else:
410 inc_dir = get_path('platinclude')
411 return os.path.join(inc_dir, 'pyconfig.h')
412
Tarek Ziadéedacea32010-01-29 11:41:03 +0000413def get_scheme_names():
Éric Araujo300623d2010-11-22 01:19:20 +0000414 """Return a tuple containing the schemes names."""
Tarek Ziadébd797682010-02-02 23:16:13 +0000415 schemes = list(_INSTALL_SCHEMES.keys())
416 schemes.sort()
417 return tuple(schemes)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000418
419def get_path_names():
Éric Araujo300623d2010-11-22 01:19:20 +0000420 """Return a tuple containing the paths names."""
Tarek Ziadéedacea32010-01-29 11:41:03 +0000421 return _SCHEME_KEYS
422
423def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
Éric Araujo300623d2010-11-22 01:19:20 +0000424 """Return a mapping containing an install scheme.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000425
426 ``scheme`` is the install scheme name. If not provided, it will
427 return the default scheme for the current platform.
428 """
429 if expand:
430 return _expand_vars(scheme, vars)
431 else:
432 return _INSTALL_SCHEMES[scheme]
433
434def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
Éric Araujo300623d2010-11-22 01:19:20 +0000435 """Return a path corresponding to the scheme.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000436
437 ``scheme`` is the install scheme name.
438 """
439 return get_paths(scheme, vars, expand)[name]
440
441def get_config_vars(*args):
442 """With no arguments, return a dictionary of all configuration
443 variables relevant for the current platform.
444
445 On Unix, this means every variable defined in Python's installed Makefile;
446 On Windows and Mac OS it's a much smaller set.
447
448 With arguments, return a list of values that result from looking up
449 each argument in the configuration variable dictionary.
450 """
451 import re
452 global _CONFIG_VARS
453 if _CONFIG_VARS is None:
454 _CONFIG_VARS = {}
455 # Normalized versions of prefix and exec_prefix are handy to have;
456 # in fact, these are the standard versions used most places in the
457 # Distutils.
458 _CONFIG_VARS['prefix'] = _PREFIX
459 _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
460 _CONFIG_VARS['py_version'] = _PY_VERSION
461 _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
462 _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]
463 _CONFIG_VARS['base'] = _PREFIX
464 _CONFIG_VARS['platbase'] = _EXEC_PREFIX
Tarek Ziadéedacea32010-01-29 11:41:03 +0000465 _CONFIG_VARS['projectbase'] = _PROJECT_BASE
Barry Warsawd5eaa5f2010-11-25 01:34:47 +0000466 try:
467 _CONFIG_VARS['abiflags'] = sys.abiflags
468 except AttributeError:
469 # sys.abiflags may not be defined on all platforms.
470 _CONFIG_VARS['abiflags'] = ''
Tarek Ziadéedacea32010-01-29 11:41:03 +0000471
472 if os.name in ('nt', 'os2'):
473 _init_non_posix(_CONFIG_VARS)
474 if os.name == 'posix':
475 _init_posix(_CONFIG_VARS)
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000476 # Setting 'userbase' is done below the call to the
477 # init function to enable using 'get_config_var' in
478 # the init-function.
479 _CONFIG_VARS['userbase'] = _getuserbase()
480
Tarek Ziadéedacea32010-01-29 11:41:03 +0000481 if 'srcdir' not in _CONFIG_VARS:
482 _CONFIG_VARS['srcdir'] = _PROJECT_BASE
Ronald Oussorenab4fd612010-06-15 21:19:50 +0000483 else:
Victor Stinnerb103a932010-10-12 22:23:23 +0000484 _CONFIG_VARS['srcdir'] = _safe_realpath(_CONFIG_VARS['srcdir'])
Tarek Ziadéedacea32010-01-29 11:41:03 +0000485
486
487 # Convert srcdir into an absolute path if it appears necessary.
488 # Normally it is relative to the build directory. However, during
489 # testing, for example, we might be running a non-installed python
490 # from a different directory.
491 if _PYTHON_BUILD and os.name == "posix":
492 base = _PROJECT_BASE
Victor Stinnerb103a932010-10-12 22:23:23 +0000493 try:
494 cwd = os.getcwd()
495 except OSError:
496 cwd = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000497 if (not os.path.isabs(_CONFIG_VARS['srcdir']) and
Victor Stinnerb103a932010-10-12 22:23:23 +0000498 base != cwd):
Tarek Ziadéedacea32010-01-29 11:41:03 +0000499 # srcdir is relative and we are not in the same directory
500 # as the executable. Assume executable is in the build
501 # directory and make srcdir absolute.
502 srcdir = os.path.join(base, _CONFIG_VARS['srcdir'])
503 _CONFIG_VARS['srcdir'] = os.path.normpath(srcdir)
504
Ned Deilyfc20d772013-01-31 01:28:23 -0800505 # OS X platforms require special customization to handle
506 # multi-architecture, multi-os-version installers
Tarek Ziadéedacea32010-01-29 11:41:03 +0000507 if sys.platform == 'darwin':
Ned Deilyfc20d772013-01-31 01:28:23 -0800508 import _osx_support
509 _osx_support.customize_config_vars(_CONFIG_VARS)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000510
511 if args:
512 vals = []
513 for name in args:
514 vals.append(_CONFIG_VARS.get(name))
515 return vals
516 else:
517 return _CONFIG_VARS
518
519def get_config_var(name):
520 """Return the value of a single variable using the dictionary returned by
521 'get_config_vars()'.
522
523 Equivalent to get_config_vars().get(name)
524 """
525 return get_config_vars().get(name)
526
527def get_platform():
528 """Return a string that identifies the current platform.
529
530 This is used mainly to distinguish platform-specific build directories and
531 platform-specific built distributions. Typically includes the OS name
532 and version and the architecture (as supplied by 'os.uname()'),
533 although the exact information included depends on the OS; eg. for IRIX
534 the architecture isn't particularly important (IRIX only runs on SGI
535 hardware), but for Linux the kernel version isn't particularly
536 important.
537
538 Examples of returned values:
539 linux-i586
540 linux-alpha (?)
541 solaris-2.6-sun4u
542 irix-5.3
543 irix64-6.2
544
545 Windows will return one of:
546 win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
547 win-ia64 (64bit Windows on Itanium)
548 win32 (all others - specifically, sys.platform is returned)
549
550 For other non-POSIX platforms, currently just returns 'sys.platform'.
551 """
552 import re
553 if os.name == 'nt':
554 # sniff sys.version for architecture.
555 prefix = " bit ("
556 i = sys.version.find(prefix)
557 if i == -1:
558 return sys.platform
559 j = sys.version.find(")", i)
560 look = sys.version[i+len(prefix):j].lower()
561 if look == 'amd64':
562 return 'win-amd64'
563 if look == 'itanium':
564 return 'win-ia64'
565 return sys.platform
566
567 if os.name != "posix" or not hasattr(os, 'uname'):
568 # XXX what about the architecture? NT is Intel or Alpha,
569 # Mac OS is M68k or PPC, etc.
570 return sys.platform
571
572 # Try to distinguish various flavours of Unix
573 osname, host, release, version, machine = os.uname()
574
575 # Convert the OS name to lowercase, remove '/' characters
576 # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
577 osname = osname.lower().replace('/', '')
578 machine = machine.replace(' ', '_')
579 machine = machine.replace('/', '-')
580
581 if osname[:5] == "linux":
582 # At least on Linux/Intel, 'machine' is the processor --
583 # i386, etc.
584 # XXX what about Alpha, SPARC, etc?
585 return "%s-%s" % (osname, machine)
586 elif osname[:5] == "sunos":
587 if release[0] >= "5": # SunOS 5 == Solaris 2
588 osname = "solaris"
589 release = "%d.%s" % (int(release[0]) - 3, release[2:])
Jesus Cea1aa1cf32012-01-18 04:49:26 +0100590 # We can't use "platform.architecture()[0]" because a
591 # bootstrap problem. We use a dict to get an error
592 # if some suspicious happens.
593 bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
Jesus Cea031605a2012-01-18 05:04:49 +0100594 machine += ".%s" % bitness[sys.maxsize]
Tarek Ziadéedacea32010-01-29 11:41:03 +0000595 # fall through to standard osname-release-machine representation
596 elif osname[:4] == "irix": # could be "irix64"!
597 return "%s-%s" % (osname, release)
598 elif osname[:3] == "aix":
599 return "%s-%s.%s" % (osname, version, release)
600 elif osname[:6] == "cygwin":
601 osname = "cygwin"
602 rel_re = re.compile (r'[\d.]+')
603 m = rel_re.match(release)
604 if m:
605 release = m.group()
606 elif osname[:6] == "darwin":
Ned Deilyfc20d772013-01-31 01:28:23 -0800607 import _osx_support
608 osname, release, machine = _osx_support.get_platform_osx(
609 get_config_vars(),
610 osname, release, machine)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000611
612 return "%s-%s-%s" % (osname, release, machine)
613
614
615def get_python_version():
616 return _PY_VERSION_SHORT
Tarek Ziadéa7514992010-05-25 09:44:36 +0000617
618def _print_dict(title, data):
619 for index, (key, value) in enumerate(sorted(data.items())):
620 if index == 0:
621 print('{0}: '.format(title))
622 print('\t{0} = "{1}"'.format(key, value))
623
624def _main():
Éric Araujo300623d2010-11-22 01:19:20 +0000625 """Display all information sysconfig detains."""
Tarek Ziadéa7514992010-05-25 09:44:36 +0000626 print('Platform: "{0}"'.format(get_platform()))
627 print('Python version: "{0}"'.format(get_python_version()))
628 print('Current installation scheme: "{0}"'.format(_get_default_scheme()))
629 print('')
630 _print_dict('Paths', get_paths())
631 print('')
632 _print_dict('Variables', get_config_vars())
633
634if __name__ == '__main__':
635 _main()