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