sysconfig.py 24 KB

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