Skip to content

Latest commit

 

History

History
723 lines (610 loc) · 24.4 KB

File metadata and controls

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