sysconfig.py 24 KB

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