sysconfig.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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.dist", "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(check_exists=False):
  293. for envvar in ('_PYTHON_SYSCONFIGDATA_NAME', '_CONDA_PYTHON_SYSCONFIGDATA_NAME'):
  294. res = os.environ.get(envvar, None)
  295. if res and check_exists:
  296. try:
  297. import importlib.util
  298. loader = importlib.util.find_spec(res)
  299. except:
  300. res = None
  301. if res:
  302. return res
  303. return '_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
  304. abi=sys.abiflags,
  305. platform=sys.platform,
  306. multiarch=getattr(sys.implementation, '_multiarch', ''))
  307. def _generate_posix_vars():
  308. """Generate the Python module containing build-time variables."""
  309. import pprint
  310. vars = {}
  311. # load the installed Makefile:
  312. makefile = get_makefile_filename()
  313. try:
  314. _parse_makefile(makefile, vars)
  315. except OSError as e:
  316. msg = "invalid Python installation: unable to open %s" % makefile
  317. if hasattr(e, "strerror"):
  318. msg = msg + " (%s)" % e.strerror
  319. raise OSError(msg)
  320. # load the installed pyconfig.h:
  321. config_h = get_config_h_filename()
  322. try:
  323. with open(config_h) as f:
  324. parse_config_h(f, vars)
  325. except OSError as e:
  326. msg = "invalid Python installation: unable to open %s" % config_h
  327. if hasattr(e, "strerror"):
  328. msg = msg + " (%s)" % e.strerror
  329. raise OSError(msg)
  330. # On AIX, there are wrong paths to the linker scripts in the Makefile
  331. # -- these paths are relative to the Python source, but when installed
  332. # the scripts are in another directory.
  333. if _PYTHON_BUILD:
  334. vars['BLDSHARED'] = vars['LDSHARED']
  335. # There's a chicken-and-egg situation on OS X with regards to the
  336. # _sysconfigdata module after the changes introduced by #15298:
  337. # get_config_vars() is called by get_platform() as part of the
  338. # `make pybuilddir.txt` target -- which is a precursor to the
  339. # _sysconfigdata.py module being constructed. Unfortunately,
  340. # get_config_vars() eventually calls _init_posix(), which attempts
  341. # to import _sysconfigdata, which we won't have built yet. In order
  342. # for _init_posix() to work, if we're on Darwin, just mock up the
  343. # _sysconfigdata module manually and populate it with the build vars.
  344. # This is more than sufficient for ensuring the subsequent call to
  345. # get_platform() succeeds.
  346. name = _get_sysconfigdata_name()
  347. if 'darwin' in sys.platform:
  348. import types
  349. module = types.ModuleType(name)
  350. module.build_time_vars = vars
  351. sys.modules[name] = module
  352. pybuilddir = 'build/lib.%s-%s' % (get_platform(), _PY_VERSION_SHORT)
  353. if hasattr(sys, "gettotalrefcount"):
  354. pybuilddir += '-pydebug'
  355. os.makedirs(pybuilddir, exist_ok=True)
  356. destfile = os.path.join(pybuilddir, name + '.py')
  357. with open(destfile, 'w', encoding='utf8') as f:
  358. f.write('# system configuration generated and used by'
  359. ' the sysconfig module\n')
  360. f.write('build_time_vars = ')
  361. pprint.pprint(vars, stream=f)
  362. # Create file used for sys.path fixup -- see Modules/getpath.c
  363. with open('pybuilddir.txt', 'w', encoding='ascii') as f:
  364. f.write(pybuilddir)
  365. def _init_posix(vars):
  366. """Initialize the module as appropriate for POSIX systems."""
  367. # _sysconfigdata is generated at build time, see _generate_posix_vars()
  368. name = _get_sysconfigdata_name(True)
  369. _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
  370. build_time_vars = _temp.build_time_vars
  371. vars.update(build_time_vars)
  372. def _init_non_posix(vars):
  373. """Initialize the module as appropriate for NT"""
  374. # set basic install directories
  375. vars['LIBDEST'] = get_path('stdlib')
  376. vars['BINLIBDEST'] = get_path('platstdlib')
  377. vars['INCLUDEPY'] = get_path('include')
  378. vars['EXT_SUFFIX'] = '.pyd'
  379. vars['EXE'] = '.exe'
  380. vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
  381. vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
  382. #
  383. # public APIs
  384. #
  385. def parse_config_h(fp, vars=None):
  386. """Parse a config.h-style file.
  387. A dictionary containing name/value pairs is returned. If an
  388. optional dictionary is passed in as the second argument, it is
  389. used instead of a new dictionary.
  390. """
  391. if vars is None:
  392. vars = {}
  393. import re
  394. define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
  395. undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
  396. while True:
  397. line = fp.readline()
  398. if not line:
  399. break
  400. m = define_rx.match(line)
  401. if m:
  402. n, v = m.group(1, 2)
  403. try:
  404. v = int(v)
  405. except ValueError:
  406. pass
  407. vars[n] = v
  408. else:
  409. m = undef_rx.match(line)
  410. if m:
  411. vars[m.group(1)] = 0
  412. return vars
  413. def get_config_h_filename():
  414. """Return the path of pyconfig.h."""
  415. if _PYTHON_BUILD:
  416. if os.name == "nt":
  417. inc_dir = os.path.join(_sys_home or _PROJECT_BASE, "PC")
  418. else:
  419. inc_dir = _sys_home or _PROJECT_BASE
  420. else:
  421. inc_dir = get_path('platinclude')
  422. return os.path.join(inc_dir, 'pyconfig.h')
  423. def get_scheme_names():
  424. """Return a tuple containing the schemes names."""
  425. return tuple(sorted(_INSTALL_SCHEMES))
  426. def get_path_names():
  427. """Return a tuple containing the paths names."""
  428. return _SCHEME_KEYS
  429. def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
  430. """Return a mapping containing an install scheme.
  431. ``scheme`` is the install scheme name. If not provided, it will
  432. return the default scheme for the current platform.
  433. """
  434. if expand:
  435. return _expand_vars(scheme, vars)
  436. else:
  437. return _INSTALL_SCHEMES[scheme]
  438. def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
  439. """Return a path corresponding to the scheme.
  440. ``scheme`` is the install scheme name.
  441. """
  442. return get_paths(scheme, vars, expand)[name]
  443. def get_config_vars(*args):
  444. """With no arguments, return a dictionary of all configuration
  445. variables relevant for the current platform.
  446. On Unix, this means every variable defined in Python's installed Makefile;
  447. On Windows it's a much smaller set.
  448. With arguments, return a list of values that result from looking up
  449. each argument in the configuration variable dictionary.
  450. """
  451. global _CONFIG_VARS
  452. if _CONFIG_VARS is None:
  453. _CONFIG_VARS = {}
  454. # Normalized versions of prefix and exec_prefix are handy to have;
  455. # in fact, these are the standard versions used most places in the
  456. # Distutils.
  457. _CONFIG_VARS['prefix'] = _PREFIX
  458. _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
  459. _CONFIG_VARS['py_version'] = _PY_VERSION
  460. _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
  461. _CONFIG_VARS['py_version_nodot'] = _PY_VERSION_SHORT_NO_DOT
  462. _CONFIG_VARS['installed_base'] = _BASE_PREFIX
  463. _CONFIG_VARS['base'] = _PREFIX
  464. _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX
  465. _CONFIG_VARS['platbase'] = _EXEC_PREFIX
  466. _CONFIG_VARS['projectbase'] = _PROJECT_BASE
  467. try:
  468. _CONFIG_VARS['abiflags'] = sys.abiflags
  469. except AttributeError:
  470. # sys.abiflags may not be defined on all platforms.
  471. _CONFIG_VARS['abiflags'] = ''
  472. if os.name == 'nt':
  473. _init_non_posix(_CONFIG_VARS)
  474. if os.name == 'posix':
  475. _init_posix(_CONFIG_VARS)
  476. # For backward compatibility, see issue19555
  477. SO = _CONFIG_VARS.get('EXT_SUFFIX')
  478. if SO is not None:
  479. _CONFIG_VARS['SO'] = SO
  480. # Setting 'userbase' is done below the call to the
  481. # init function to enable using 'get_config_var' in
  482. # the init-function.
  483. _CONFIG_VARS['userbase'] = _getuserbase()
  484. # Always convert srcdir to an absolute path
  485. srcdir = _CONFIG_VARS.get('srcdir', _PROJECT_BASE)
  486. if os.name == 'posix':
  487. if _PYTHON_BUILD:
  488. # If srcdir is a relative path (typically '.' or '..')
  489. # then it should be interpreted relative to the directory
  490. # containing Makefile.
  491. base = os.path.dirname(get_makefile_filename())
  492. srcdir = os.path.join(base, srcdir)
  493. else:
  494. # srcdir is not meaningful since the installation is
  495. # spread about the filesystem. We choose the
  496. # directory containing the Makefile since we know it
  497. # exists.
  498. srcdir = os.path.dirname(get_makefile_filename())
  499. _CONFIG_VARS['srcdir'] = _safe_realpath(srcdir)
  500. # OS X platforms require special customization to handle
  501. # multi-architecture, multi-os-version installers
  502. if sys.platform == 'darwin':
  503. import _osx_support
  504. _osx_support.customize_config_vars(_CONFIG_VARS)
  505. if args:
  506. vals = []
  507. for name in args:
  508. vals.append(_CONFIG_VARS.get(name))
  509. return vals
  510. else:
  511. return _CONFIG_VARS
  512. def get_config_var(name):
  513. """Return the value of a single variable using the dictionary returned by
  514. 'get_config_vars()'.
  515. Equivalent to get_config_vars().get(name)
  516. """
  517. if name == 'SO':
  518. import warnings
  519. warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
  520. return get_config_vars().get(name)
  521. def get_platform():
  522. """Return a string that identifies the current platform.
  523. This is used mainly to distinguish platform-specific build directories and
  524. platform-specific built distributions. Typically includes the OS name and
  525. version and the architecture (as supplied by 'os.uname()'), although the
  526. exact information included depends on the OS; on Linux, the kernel version
  527. isn't particularly important.
  528. Examples of returned values:
  529. linux-i586
  530. linux-alpha (?)
  531. solaris-2.6-sun4u
  532. Windows will return one of:
  533. win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  534. win32 (all others - specifically, sys.platform is returned)
  535. For other non-POSIX platforms, currently just returns 'sys.platform'.
  536. """
  537. if os.name == 'nt':
  538. if 'amd64' in sys.version.lower():
  539. return 'win-amd64'
  540. return sys.platform
  541. if os.name != "posix" or not hasattr(os, 'uname'):
  542. # XXX what about the architecture? NT is Intel or Alpha
  543. return sys.platform
  544. # Set for cross builds explicitly
  545. if "_PYTHON_HOST_PLATFORM" in os.environ:
  546. return os.environ["_PYTHON_HOST_PLATFORM"]
  547. # Try to distinguish various flavours of Unix
  548. osname, host, release, version, machine = os.uname()
  549. # Convert the OS name to lowercase, remove '/' characters, and translate
  550. # spaces (for "Power Macintosh")
  551. osname = osname.lower().replace('/', '')
  552. machine = machine.replace(' ', '_')
  553. machine = machine.replace('/', '-')
  554. if osname[:5] == "linux":
  555. # At least on Linux/Intel, 'machine' is the processor --
  556. # i386, etc.
  557. # XXX what about Alpha, SPARC, etc?
  558. return "%s-%s" % (osname, machine)
  559. elif osname[:5] == "sunos":
  560. if release[0] >= "5": # SunOS 5 == Solaris 2
  561. osname = "solaris"
  562. release = "%d.%s" % (int(release[0]) - 3, release[2:])
  563. # We can't use "platform.architecture()[0]" because a
  564. # bootstrap problem. We use a dict to get an error
  565. # if some suspicious happens.
  566. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
  567. machine += ".%s" % bitness[sys.maxsize]
  568. # fall through to standard osname-release-machine representation
  569. elif osname[:3] == "aix":
  570. return "%s-%s.%s" % (osname, version, release)
  571. elif osname[:6] == "cygwin":
  572. osname = "cygwin"
  573. import re
  574. rel_re = re.compile(r'[\d.]+')
  575. m = rel_re.match(release)
  576. if m:
  577. release = m.group()
  578. elif osname[:6] == "darwin":
  579. import _osx_support
  580. osname, release, machine = _osx_support.get_platform_osx(
  581. get_config_vars(),
  582. osname, release, machine)
  583. return "%s-%s-%s" % (osname, release, machine)
  584. def get_python_version():
  585. return _PY_VERSION_SHORT
  586. def _print_dict(title, data):
  587. for index, (key, value) in enumerate(sorted(data.items())):
  588. if index == 0:
  589. print('%s: ' % (title))
  590. print('\t%s = "%s"' % (key, value))
  591. def _main():
  592. """Display all information sysconfig detains."""
  593. if '--generate-posix-vars' in sys.argv:
  594. _generate_posix_vars()
  595. return
  596. print('Platform: "%s"' % get_platform())
  597. print('Python version: "%s"' % get_python_version())
  598. print('Current installation scheme: "%s"' % _get_default_scheme())
  599. print()
  600. _print_dict('Paths', get_paths())
  601. print()
  602. _print_dict('Variables', get_config_vars())
  603. if __name__ == '__main__':
  604. _main()