sysconfig.py 25 KB

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