PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/sysconfig.py

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