sysconfig.py 30 KB

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