sysconfig.py 24 KB

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