blob: bf04ac541e6b027f3be0a96f874088c3ea6626f7 [file] [log] [blame]
Tarek Ziade1231a4e2011-05-19 13:07:25 +02001"""Access to Python's configuration information."""
Tarek Ziadéedacea32010-01-29 11:41:03 +00002
Tarek Ziadéedacea32010-01-29 11:41:03 +00003import os
Tarek Ziade1231a4e2011-05-19 13:07:25 +02004import sys
Florent Xiclunaa4707382010-03-11 00:05:17 +00005from os.path import pardir, realpath
Tarek Ziadéedacea32010-01-29 11:41:03 +00006
Barry Warsawebbef6f2010-09-20 15:29:53 +00007__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',
Tarek Ziade1231a4e2011-05-19 13:07:25 +020019]
Tarek Ziadé16ed6cb2010-05-25 09:47:06 +000020
Éric Araujoec177c12012-06-24 03:27:43 -040021_INSTALL_SCHEMES = {
22 'posix_prefix': {
Victor Stinner8510f432020-03-10 09:53:09 +010023 'stdlib': '{installed_base}/{platlibdir}/python{py_version_short}',
24 'platstdlib': '{platbase}/{platlibdir}/python{py_version_short}',
Éric Araujoec177c12012-06-24 03:27:43 -040025 'purelib': '{base}/lib/python{py_version_short}/site-packages',
Victor Stinner8510f432020-03-10 09:53:09 +010026 'platlib': '{platbase}/{platlibdir}/python{py_version_short}/site-packages',
Éric Araujoec177c12012-06-24 03:27:43 -040027 '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 },
INADA Naokia8f8d5b2017-06-29 00:31:53 +090054 # NOTE: When modifying "purelib" scheme, update site._get_path() too.
Éric Araujoec177c12012-06-24 03:27:43 -040055 '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',
Steve Dower17be5142015-02-14 09:50:59 -080061 'scripts': '{userbase}/Python{py_version_nodot}/Scripts',
Éric Araujoec177c12012-06-24 03:27:43 -040062 'data': '{userbase}',
63 },
64 'posix_user': {
Victor Stinner8510f432020-03-10 09:53:09 +010065 'stdlib': '{userbase}/{platlibdir}/python{py_version_short}',
66 'platstdlib': '{userbase}/{platlibdir}/python{py_version_short}',
Éric Araujoec177c12012-06-24 03:27:43 -040067 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
Victor Stinner8510f432020-03-10 09:53:09 +010068 'platlib': '{userbase}/{platlibdir}/python{py_version_short}/site-packages',
Éric Araujoec177c12012-06-24 03:27:43 -040069 '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 }
Tarek Ziadéedacea32010-01-29 11:41:03 +000083
Éric Araujoec177c12012-06-24 03:27:43 -040084_SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
85 'scripts', 'data')
Tarek Ziade1231a4e2011-05-19 13:07:25 +020086
Tarek Ziadéedacea32010-01-29 11:41:03 +000087_PY_VERSION = sys.version.split()[0]
Serhiy Storchaka885bdc42016-02-11 13:10:36 +020088_PY_VERSION_SHORT = '%d.%d' % sys.version_info[:2]
89_PY_VERSION_SHORT_NO_DOT = '%d%d' % sys.version_info[:2]
Tarek Ziadéedacea32010-01-29 11:41:03 +000090_PREFIX = os.path.normpath(sys.prefix)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010091_BASE_PREFIX = os.path.normpath(sys.base_prefix)
Tarek Ziadéedacea32010-01-29 11:41:03 +000092_EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010093_BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
Tarek Ziadéedacea32010-01-29 11:41:03 +000094_CONFIG_VARS = None
95_USER_BASE = None
Victor Stinnerb103a932010-10-12 22:23:23 +000096
Tarek Ziade1231a4e2011-05-19 13:07:25 +020097
Victor Stinnerb103a932010-10-12 22:23:23 +000098def _safe_realpath(path):
99 try:
100 return realpath(path)
101 except OSError:
102 return path
103
Victor Stinner171ba052010-03-12 14:20:59 +0000104if sys.executable:
Victor Stinnerb103a932010-10-12 22:23:23 +0000105 _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
Victor Stinner171ba052010-03-12 14:20:59 +0000106else:
107 # sys.executable can be empty if argv[0] has been changed and Python is
108 # unable to retrieve the real program name
Victor Stinnerb103a932010-10-12 22:23:23 +0000109 _PROJECT_BASE = _safe_realpath(os.getcwd())
Tarek Ziadéedacea32010-01-29 11:41:03 +0000110
Steve Dower65e4cb12014-11-22 12:54:57 -0800111if (os.name == 'nt' and
112 _PROJECT_BASE.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
Victor Stinnerb103a932010-10-12 22:23:23 +0000113 _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir))
Tarek Ziadéedacea32010-01-29 11:41:03 +0000114
doko@ubuntu.com1abe1c52012-06-30 20:42:45 +0200115# set for cross builds
doko@ubuntu.com7e6c2e22012-06-30 22:35:00 +0200116if "_PYTHON_PROJECT_BASE" in os.environ:
117 _PROJECT_BASE = _safe_realpath(os.environ["_PYTHON_PROJECT_BASE"])
doko@ubuntu.com1abe1c52012-06-30 20:42:45 +0200118
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100119def _is_python_source_dir(d):
Antoine Pitrou961d54c2018-07-16 19:03:03 +0200120 for fn in ("Setup", "Setup.local"):
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100121 if os.path.isfile(os.path.join(d, "Modules", fn)):
Tarek Ziadéedacea32010-01-29 11:41:03 +0000122 return True
123 return False
124
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100125_sys_home = getattr(sys, '_home', None)
Steve Dower85e102a2019-02-04 17:15:13 -0800126
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
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100136def 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)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000142
143if _PYTHON_BUILD:
144 for scheme in ('posix_prefix', 'posix_home'):
Éric Araujoec177c12012-06-24 03:27:43 -0400145 _INSTALL_SCHEMES[scheme]['include'] = '{srcdir}/Include'
146 _INSTALL_SCHEMES[scheme]['platinclude'] = '{projectbase}/.'
Tarek Ziadéedacea32010-01-29 11:41:03 +0000147
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200148
Éric Araujoec177c12012-06-24 03:27:43 -0400149def _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:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300156 raise AttributeError('{%s}' % var) from None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000157
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
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200165
Tarek Ziadéedacea32010-01-29 11:41:03 +0000166def _expand_vars(scheme, vars):
167 res = {}
168 if vars is None:
169 vars = {}
170 _extend_dict(vars, get_config_vars())
171
Éric Araujoec177c12012-06-24 03:27:43 -0400172 for key, value in _INSTALL_SCHEMES[scheme].items():
Tarek Ziadéedacea32010-01-29 11:41:03 +0000173 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
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200178
Tarek Ziadéedacea32010-01-29 11:41:03 +0000179def _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
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200185
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900186# NOTE: site.py has copy of this function.
187# Sync it when modify this function.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000188def _getuserbase():
189 env_base = os.environ.get("PYTHONUSERBASE", None)
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900190 if env_base:
191 return env_base
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200192
Tarek Ziadéedacea32010-01-29 11:41:03 +0000193 def joinuser(*args):
194 return os.path.expanduser(os.path.join(*args))
195
Tarek Ziadéedacea32010-01-29 11:41:03 +0000196 if os.name == "nt":
197 base = os.environ.get("APPDATA") or "~"
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900198 return joinuser(base, "Python")
Tarek Ziadéedacea32010-01-29 11:41:03 +0000199
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900200 if sys.platform == "darwin" and sys._framework:
201 return joinuser("~", "Library", sys._framework,
202 "%d.%d" % sys.version_info[:2])
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000203
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900204 return joinuser("~", ".local")
Tarek Ziadéedacea32010-01-29 11:41:03 +0000205
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 """
Tarek Ziadéedacea32010-01-29 11:41:03 +0000214 # Regexes needed for parsing Makefile (and similar syntaxes,
215 # like old-style Setup files).
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200216 import re
R David Murray44b548d2016-09-08 13:59:53 -0400217 _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
Tarek Ziadéedacea32010-01-29 11:41:03 +0000218 _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
Victor Stinner75d8c5c2010-10-23 17:02:31 +0000226 with open(filename, errors="surrogateescape") as f:
Tarek Ziadéedacea32010-01-29 11:41:03 +0000227 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
Ronald Oussorend21886c2010-07-20 16:07:10 +0000253 # 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
Tarek Ziadéedacea32010-01-29 11:41:03 +0000259 while len(variables) > 0:
260 for name in tuple(variables):
261 value = notdone[name]
doko@ubuntu.comb2b12172016-01-11 21:41:40 +0100262 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
Tarek Ziadéedacea32010-01-29 11:41:03 +0000268 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]
Ronald Oussorend21886c2010-07-20 16:07:10 +0000279
280 elif n in renamed_variables:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200281 if (name.startswith('PY_') and
282 name[3:] in renamed_variables):
Ronald Oussorend21886c2010-07-20 16:07:10 +0000283 item = ""
284
285 elif 'PY_' + n in notdone:
286 found = False
287
288 else:
289 item = str(done['PY_' + n])
290
Tarek Ziadéedacea32010-01-29 11:41:03 +0000291 else:
292 done[n] = item = ""
Ronald Oussorend21886c2010-07-20 16:07:10 +0000293
Tarek Ziadéedacea32010-01-29 11:41:03 +0000294 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)
Ronald Oussorend21886c2010-07-20 16:07:10 +0000307
308 if name.startswith('PY_') \
Victor Stinner1273b7c2011-05-24 23:37:07 +0200309 and name[3:] in renamed_variables:
Ronald Oussorend21886c2010-07-20 16:07:10 +0000310
311 name = name[3:]
312 if name not in done:
313 done[name] = value
314
Tarek Ziadéedacea32010-01-29 11:41:03 +0000315 else:
Victor Stinner1273b7c2011-05-24 23:37:07 +0200316 # bogus variable reference (e.g. "prefix=$/opt/python");
317 # just drop it since we can't deal
318 done[name] = value
Tarek Ziadéedacea32010-01-29 11:41:03 +0000319 variables.remove(name)
320
Antoine Pitroudbec7802010-10-10 09:37:12 +0000321 # strip spurious spaces
322 for k, v in done.items():
323 if isinstance(v, str):
324 done[k] = v.strip()
325
Tarek Ziadéedacea32010-01-29 11:41:03 +0000326 # save the results in the global dictionary
327 vars.update(done)
328 return vars
329
Tarek Ziadéedacea32010-01-29 11:41:03 +0000330
Barry Warsawebbef6f2010-09-20 15:29:53 +0000331def get_makefile_filename():
Éric Araujo300623d2010-11-22 01:19:20 +0000332 """Return the path of the Makefile."""
Tarek Ziadéedacea32010-01-29 11:41:03 +0000333 if _PYTHON_BUILD:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100334 return os.path.join(_sys_home or _PROJECT_BASE, "Makefile")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200335 if hasattr(sys, 'abiflags'):
336 config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags)
337 else:
338 config_dir_name = 'config'
doko@ubuntu.com55532312016-06-14 08:55:19 +0200339 if hasattr(sys.implementation, '_multiarch'):
340 config_dir_name += '-%s' % sys.implementation._multiarch
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200341 return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
Tarek Ziadéedacea32010-01-29 11:41:03 +0000342
Zachary Warec4b53af2016-09-09 17:59:49 -0700343
Xavier de Gaye92dec542016-09-11 22:22:24 +0200344def _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 ))
Zachary Warec4b53af2016-09-09 17:59:49 -0700351
352
Antoine Pitrou1e73a242011-10-18 17:52:24 +0200353def _generate_posix_vars():
354 """Generate the Python module containing build-time variables."""
355 import pprint
356 vars = {}
Tarek Ziadéedacea32010-01-29 11:41:03 +0000357 # load the installed Makefile:
Barry Warsawebbef6f2010-09-20 15:29:53 +0000358 makefile = get_makefile_filename()
Tarek Ziadéedacea32010-01-29 11:41:03 +0000359 try:
360 _parse_makefile(makefile, vars)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200361 except OSError as e:
Tarek Ziadéedacea32010-01-29 11:41:03 +0000362 msg = "invalid Python installation: unable to open %s" % makefile
363 if hasattr(e, "strerror"):
364 msg = msg + " (%s)" % e.strerror
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200365 raise OSError(msg)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000366 # load the installed pyconfig.h:
367 config_h = get_config_h_filename()
368 try:
Antoine Pitroub86680e2010-10-14 21:15:17 +0000369 with open(config_h) as f:
370 parse_config_h(f, vars)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200371 except OSError as e:
Tarek Ziadéedacea32010-01-29 11:41:03 +0000372 msg = "invalid Python installation: unable to open %s" % config_h
373 if hasattr(e, "strerror"):
374 msg = msg + " (%s)" % e.strerror
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200375 raise OSError(msg)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000376 # 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:
Antoine Pitrou0abb2182013-10-19 22:05:05 +0200380 vars['BLDSHARED'] = vars['LDSHARED']
Victor Stinner65651ea2011-10-20 00:41:21 +0200381
Trent Nelsonee528cc2012-10-17 04:23:50 -0400382 # 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
Trent Nelsonecbe2a92012-10-17 18:03:24 -0400388 # 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.
Xavier de Gaye92dec542016-09-11 22:22:24 +0200393 name = _get_sysconfigdata_name()
Trent Nelsonecbe2a92012-10-17 18:03:24 -0400394 if 'darwin' in sys.platform:
Brett Cannonf15a59f2013-06-15 14:32:11 -0400395 import types
396 module = types.ModuleType(name)
Trent Nelsonecbe2a92012-10-17 18:03:24 -0400397 module.build_time_vars = vars
398 sys.modules[name] = module
Tarek Ziadéedacea32010-01-29 11:41:03 +0000399
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200400 pybuilddir = 'build/lib.%s-%s' % (get_platform(), _PY_VERSION_SHORT)
Trent Nelsonee528cc2012-10-17 04:23:50 -0400401 if hasattr(sys, "gettotalrefcount"):
402 pybuilddir += '-pydebug'
403 os.makedirs(pybuilddir, exist_ok=True)
Trent Nelsonecbe2a92012-10-17 18:03:24 -0400404 destfile = os.path.join(pybuilddir, name + '.py')
Trent Nelsonee528cc2012-10-17 04:23:50 -0400405
Trent Nelsonecbe2a92012-10-17 18:03:24 -0400406 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)
Trent Nelsonee528cc2012-10-17 04:23:50 -0400411
Trent Nelsonc101bf32012-10-16 08:13:12 -0400412 # Create file used for sys.path fixup -- see Modules/getpath.c
Victor Stinner52ad33a2019-09-25 02:10:35 +0200413 with open('pybuilddir.txt', 'w', encoding='utf8') as f:
Trent Nelsonc101bf32012-10-16 08:13:12 -0400414 f.write(pybuilddir)
415
Antoine Pitrou1e73a242011-10-18 17:52:24 +0200416def _init_posix(vars):
417 """Initialize the module as appropriate for POSIX systems."""
418 # _sysconfigdata is generated at build time, see _generate_posix_vars()
Zachary Warec4b53af2016-09-09 17:59:49 -0700419 name = _get_sysconfigdata_name()
doko@ubuntu.com55532312016-06-14 08:55:19 +0200420 _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
421 build_time_vars = _temp.build_time_vars
Antoine Pitrou1e73a242011-10-18 17:52:24 +0200422 vars.update(build_time_vars)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200423
Tarek Ziadéedacea32010-01-29 11:41:03 +0000424def _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')
doko@ubuntu.comd5537d02013-03-21 13:21:49 -0700430 vars['EXT_SUFFIX'] = '.pyd'
Tarek Ziadéedacea32010-01-29 11:41:03 +0000431 vars['EXE'] = '.exe'
432 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
Victor Stinnerb103a932010-10-12 22:23:23 +0000433 vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
Tarek Ziadéedacea32010-01-29 11:41:03 +0000434
435#
436# public APIs
437#
438
Tarek Ziadébd797682010-02-02 23:16:13 +0000439
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 """
Tarek Ziadébd797682010-02-02 23:16:13 +0000447 if vars is None:
448 vars = {}
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200449 import re
Tarek Ziadébd797682010-02-02 23:16:13 +0000450 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)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200460 try:
461 v = int(v)
462 except ValueError:
463 pass
Tarek Ziadébd797682010-02-02 23:16:13 +0000464 vars[n] = v
465 else:
466 m = undef_rx.match(line)
467 if m:
468 vars[m.group(1)] = 0
469 return vars
470
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200471
Tarek Ziadébd797682010-02-02 23:16:13 +0000472def get_config_h_filename():
Éric Araujo300623d2010-11-22 01:19:20 +0000473 """Return the path of pyconfig.h."""
Tarek Ziadébd797682010-02-02 23:16:13 +0000474 if _PYTHON_BUILD:
475 if os.name == "nt":
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100476 inc_dir = os.path.join(_sys_home or _PROJECT_BASE, "PC")
Tarek Ziadébd797682010-02-02 23:16:13 +0000477 else:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100478 inc_dir = _sys_home or _PROJECT_BASE
Tarek Ziadébd797682010-02-02 23:16:13 +0000479 else:
480 inc_dir = get_path('platinclude')
481 return os.path.join(inc_dir, 'pyconfig.h')
482
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200483
Tarek Ziadéedacea32010-01-29 11:41:03 +0000484def get_scheme_names():
Éric Araujo300623d2010-11-22 01:19:20 +0000485 """Return a tuple containing the schemes names."""
Éric Araujoec177c12012-06-24 03:27:43 -0400486 return tuple(sorted(_INSTALL_SCHEMES))
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200487
Tarek Ziadéedacea32010-01-29 11:41:03 +0000488
489def get_path_names():
Éric Araujo300623d2010-11-22 01:19:20 +0000490 """Return a tuple containing the paths names."""
Éric Araujoec177c12012-06-24 03:27:43 -0400491 return _SCHEME_KEYS
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200492
Tarek Ziadéedacea32010-01-29 11:41:03 +0000493
494def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
Éric Araujo300623d2010-11-22 01:19:20 +0000495 """Return a mapping containing an install scheme.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000496
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:
Éric Araujoec177c12012-06-24 03:27:43 -0400503 return _INSTALL_SCHEMES[scheme]
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200504
Tarek Ziadéedacea32010-01-29 11:41:03 +0000505
506def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
Éric Araujo300623d2010-11-22 01:19:20 +0000507 """Return a path corresponding to the scheme.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000508
509 ``scheme`` is the install scheme name.
510 """
511 return get_paths(scheme, vars, expand)[name]
512
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200513
Tarek Ziadéedacea32010-01-29 11:41:03 +0000514def 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;
Ned Deilydf8aa2b2012-07-21 05:36:30 -0700519 On Windows it's a much smaller set.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000520
521 With arguments, return a list of values that result from looking up
522 each argument in the configuration variable dictionary.
523 """
Tarek Ziadéedacea32010-01-29 11:41:03 +0000524 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
Éric Araujo859aad62012-06-24 00:07:41 -0400529 # Distutils.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000530 _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
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200534 _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100535 _CONFIG_VARS['installed_base'] = _BASE_PREFIX
Tarek Ziadéedacea32010-01-29 11:41:03 +0000536 _CONFIG_VARS['base'] = _PREFIX
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100537 _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX
Tarek Ziadéedacea32010-01-29 11:41:03 +0000538 _CONFIG_VARS['platbase'] = _EXEC_PREFIX
Tarek Ziadéedacea32010-01-29 11:41:03 +0000539 _CONFIG_VARS['projectbase'] = _PROJECT_BASE
Victor Stinner8510f432020-03-10 09:53:09 +0100540 _CONFIG_VARS['platlibdir'] = sys.platlibdir
Barry Warsawd5eaa5f2010-11-25 01:34:47 +0000541 try:
542 _CONFIG_VARS['abiflags'] = sys.abiflags
543 except AttributeError:
544 # sys.abiflags may not be defined on all platforms.
545 _CONFIG_VARS['abiflags'] = ''
Tarek Ziadéedacea32010-01-29 11:41:03 +0000546
Jesus Cea4791a242012-10-05 03:15:39 +0200547 if os.name == 'nt':
Tarek Ziadéedacea32010-01-29 11:41:03 +0000548 _init_non_posix(_CONFIG_VARS)
Paul Ganssle62972d92020-05-16 04:20:06 -0400549 _CONFIG_VARS['TZPATH'] = ''
Tarek Ziadéedacea32010-01-29 11:41:03 +0000550 if os.name == 'posix':
551 _init_posix(_CONFIG_VARS)
Barry Warsaw87b96372013-11-22 11:08:05 -0500552 # For backward compatibility, see issue19555
553 SO = _CONFIG_VARS.get('EXT_SUFFIX')
554 if SO is not None:
555 _CONFIG_VARS['SO'] = SO
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000556 # Setting 'userbase' is done below the call to the
557 # init function to enable using 'get_config_var' in
558 # the init-function.
Éric Araujo2a7cc532011-11-07 09:18:30 +0100559 _CONFIG_VARS['userbase'] = _getuserbase()
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000560
Richard Oudkerk46874ad2012-07-27 12:06:55 +0100561 # 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)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000577
Ned Deilydf8aa2b2012-07-21 05:36:30 -0700578 # OS X platforms require special customization to handle
579 # multi-architecture, multi-os-version installers
Tarek Ziadéedacea32010-01-29 11:41:03 +0000580 if sys.platform == 'darwin':
Ned Deilydf8aa2b2012-07-21 05:36:30 -0700581 import _osx_support
582 _osx_support.customize_config_vars(_CONFIG_VARS)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000583
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
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200592
Tarek Ziadéedacea32010-01-29 11:41:03 +0000593def 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 """
Barry Warsaw197a7702013-11-21 18:57:14 -0500599 if name == 'SO':
600 import warnings
Serhiy Storchakaeaec3592013-11-26 17:08:24 +0200601 warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000602 return get_config_vars().get(name)
603
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200604
Tarek Ziadéedacea32010-01-29 11:41:03 +0000605def get_platform():
606 """Return a string that identifies the current platform.
607
608 This is used mainly to distinguish platform-specific build directories and
Benjamin Peterson06930632017-09-04 16:36:05 -0700609 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.
Tarek Ziadéedacea32010-01-29 11:41:03 +0000613
614 Examples of returned values:
615 linux-i586
616 linux-alpha (?)
617 solaris-2.6-sun4u
Tarek Ziadéedacea32010-01-29 11:41:03 +0000618
619 Windows will return one of:
620 win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000621 win32 (all others - specifically, sys.platform is returned)
622
623 For other non-POSIX platforms, currently just returns 'sys.platform'.
Benjamin Peterson06930632017-09-04 16:36:05 -0700624
Tarek Ziadéedacea32010-01-29 11:41:03 +0000625 """
Tarek Ziadéedacea32010-01-29 11:41:03 +0000626 if os.name == 'nt':
Zachary Ware49ce74e2017-09-06 15:45:25 -0700627 if 'amd64' in sys.version.lower():
Tarek Ziadéedacea32010-01-29 11:41:03 +0000628 return 'win-amd64'
Paul Monson62dfd7d2019-04-25 11:36:45 -0700629 if '(arm)' in sys.version.lower():
630 return 'win-arm32'
Paul Monsondaf62622019-06-12 10:16:49 -0700631 if '(arm64)' in sys.version.lower():
632 return 'win-arm64'
Tarek Ziadéedacea32010-01-29 11:41:03 +0000633 return sys.platform
634
635 if os.name != "posix" or not hasattr(os, 'uname'):
Ned Deilydf8aa2b2012-07-21 05:36:30 -0700636 # XXX what about the architecture? NT is Intel or Alpha
Tarek Ziadéedacea32010-01-29 11:41:03 +0000637 return sys.platform
638
doko@ubuntu.com1abe1c52012-06-30 20:42:45 +0200639 # Set for cross builds explicitly
640 if "_PYTHON_HOST_PLATFORM" in os.environ:
641 return os.environ["_PYTHON_HOST_PLATFORM"]
642
Tarek Ziadéedacea32010-01-29 11:41:03 +0000643 # Try to distinguish various flavours of Unix
644 osname, host, release, version, machine = os.uname()
645
Benjamin Peterson288d1da2017-09-28 22:44:27 -0700646 # Convert the OS name to lowercase, remove '/' characters, and translate
647 # spaces (for "Power Macintosh")
Tarek Ziadéedacea32010-01-29 11:41:03 +0000648 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:])
Jesus Cea1aa1cf32012-01-18 04:49:26 +0100661 # 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"}
Jesus Cea031605a2012-01-18 05:04:49 +0100665 machine += ".%s" % bitness[sys.maxsize]
Tarek Ziadéedacea32010-01-29 11:41:03 +0000666 # fall through to standard osname-release-machine representation
Tarek Ziadéedacea32010-01-29 11:41:03 +0000667 elif osname[:3] == "aix":
Michael Felt39afa2d2019-12-15 15:17:53 +0100668 from _aix_support import aix_platform
669 return aix_platform()
Tarek Ziadéedacea32010-01-29 11:41:03 +0000670 elif osname[:6] == "cygwin":
671 osname = "cygwin"
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200672 import re
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200673 rel_re = re.compile(r'[\d.]+')
Tarek Ziadéedacea32010-01-29 11:41:03 +0000674 m = rel_re.match(release)
675 if m:
676 release = m.group()
677 elif osname[:6] == "darwin":
Ned Deilydf8aa2b2012-07-21 05:36:30 -0700678 import _osx_support
679 osname, release, machine = _osx_support.get_platform_osx(
680 get_config_vars(),
681 osname, release, machine)
Tarek Ziadéedacea32010-01-29 11:41:03 +0000682
683 return "%s-%s-%s" % (osname, release, machine)
684
685
686def get_python_version():
687 return _PY_VERSION_SHORT
Tarek Ziadéa7514992010-05-25 09:44:36 +0000688
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200689
Tarek Ziadéa7514992010-05-25 09:44:36 +0000690def _print_dict(title, data):
691 for index, (key, value) in enumerate(sorted(data.items())):
692 if index == 0:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200693 print('%s: ' % (title))
694 print('\t%s = "%s"' % (key, value))
695
Tarek Ziadéa7514992010-05-25 09:44:36 +0000696
697def _main():
Éric Araujo300623d2010-11-22 01:19:20 +0000698 """Display all information sysconfig detains."""
Antoine Pitrou1e73a242011-10-18 17:52:24 +0200699 if '--generate-posix-vars' in sys.argv:
700 _generate_posix_vars()
701 return
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200702 print('Platform: "%s"' % get_platform())
703 print('Python version: "%s"' % get_python_version())
704 print('Current installation scheme: "%s"' % _get_default_scheme())
Éric Araujo559b5f12011-05-25 18:21:43 +0200705 print()
Tarek Ziadéa7514992010-05-25 09:44:36 +0000706 _print_dict('Paths', get_paths())
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200707 print()
Tarek Ziadéa7514992010-05-25 09:44:36 +0000708 _print_dict('Variables', get_config_vars())
709
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200710
Tarek Ziadéa7514992010-05-25 09:44:36 +0000711if __name__ == '__main__':
712 _main()