PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/platform.py

https://bitbucket.org/timfel/pypy
Python | 1617 lines | 1487 code | 14 blank | 116 comment | 6 complexity | b86e5b68277c1cdaa011c7ec1d8e2d3f MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env python
  2. """ This module tries to retrieve as much platform-identifying data as
  3. possible. It makes this information available via function APIs.
  4. If called from the command line, it prints the platform
  5. information concatenated as single string to stdout. The output
  6. format is useable as part of a filename.
  7. """
  8. # This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
  9. # If you find problems, please submit bug reports/patches via the
  10. # Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
  11. #
  12. # Note: Please keep this module compatible to Python 1.5.2.
  13. #
  14. # Still needed:
  15. # * more support for WinCE
  16. # * support for MS-DOS (PythonDX ?)
  17. # * support for Amiga and other still unsupported platforms running Python
  18. # * support for additional Linux distributions
  19. #
  20. # Many thanks to all those who helped adding platform-specific
  21. # checks (in no particular order):
  22. #
  23. # Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
  24. # Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
  25. # Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
  26. # Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
  27. # Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
  28. # Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter, Steve
  29. # Dower
  30. #
  31. # History:
  32. #
  33. # <see CVS and SVN checkin messages for history>
  34. #
  35. # 1.0.8 - changed Windows support to read version from kernel32.dll
  36. # 1.0.7 - added DEV_NULL
  37. # 1.0.6 - added linux_distribution()
  38. # 1.0.5 - fixed Java support to allow running the module on Jython
  39. # 1.0.4 - added IronPython support
  40. # 1.0.3 - added normalization of Windows system name
  41. # 1.0.2 - added more Windows support
  42. # 1.0.1 - reformatted to make doc.py happy
  43. # 1.0.0 - reformatted a bit and checked into Python CVS
  44. # 0.8.0 - added sys.version parser and various new access
  45. # APIs (python_version(), python_compiler(), etc.)
  46. # 0.7.2 - fixed architecture() to use sizeof(pointer) where available
  47. # 0.7.1 - added support for Caldera OpenLinux
  48. # 0.7.0 - some fixes for WinCE; untabified the source file
  49. # 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
  50. # vms_lib.getsyi() configured
  51. # 0.6.1 - added code to prevent 'uname -p' on platforms which are
  52. # known not to support it
  53. # 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
  54. # did some cleanup of the interfaces - some APIs have changed
  55. # 0.5.5 - fixed another type in the MacOS code... should have
  56. # used more coffee today ;-)
  57. # 0.5.4 - fixed a few typos in the MacOS code
  58. # 0.5.3 - added experimental MacOS support; added better popen()
  59. # workarounds in _syscmd_ver() -- still not 100% elegant
  60. # though
  61. # 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
  62. # return values (the system uname command tends to return
  63. # 'unknown' instead of just leaving the field empty)
  64. # 0.5.1 - included code for slackware dist; added exception handlers
  65. # to cover up situations where platforms don't have os.popen
  66. # (e.g. Mac) or fail on socket.gethostname(); fixed libc
  67. # detection RE
  68. # 0.5.0 - changed the API names referring to system commands to *syscmd*;
  69. # added java_ver(); made syscmd_ver() a private
  70. # API (was system_ver() in previous versions) -- use uname()
  71. # instead; extended the win32_ver() to also return processor
  72. # type information
  73. # 0.4.0 - added win32_ver() and modified the platform() output for WinXX
  74. # 0.3.4 - fixed a bug in _follow_symlinks()
  75. # 0.3.3 - fixed popen() and "file" command invokation bugs
  76. # 0.3.2 - added architecture() API and support for it in platform()
  77. # 0.3.1 - fixed syscmd_ver() RE to support Windows NT
  78. # 0.3.0 - added system alias support
  79. # 0.2.3 - removed 'wince' again... oh well.
  80. # 0.2.2 - added 'wince' to syscmd_ver() supported platforms
  81. # 0.2.1 - added cache logic and changed the platform string format
  82. # 0.2.0 - changed the API to use functions instead of module globals
  83. # since some action take too long to be run on module import
  84. # 0.1.0 - first release
  85. #
  86. # You can always get the latest version of this module at:
  87. #
  88. # http://www.egenix.com/files/python/platform.py
  89. #
  90. # If that URL should fail, try contacting the author.
  91. __copyright__ = """
  92. Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
  93. Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
  94. Permission to use, copy, modify, and distribute this software and its
  95. documentation for any purpose and without fee or royalty is hereby granted,
  96. provided that the above copyright notice appear in all copies and that
  97. both that copyright notice and this permission notice appear in
  98. supporting documentation or portions thereof, including modifications,
  99. that you make.
  100. EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
  101. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  102. FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
  103. INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  104. FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  105. NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  106. WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
  107. """
  108. __version__ = '1.0.7'
  109. import sys,string,os,re
  110. ### Globals & Constants
  111. # Determine the platform's /dev/null device
  112. try:
  113. DEV_NULL = os.devnull
  114. except AttributeError:
  115. # os.devnull was added in Python 2.4, so emulate it for earlier
  116. # Python versions
  117. if sys.platform in ('dos','win32','win16','os2'):
  118. # Use the old CP/M NUL as device name
  119. DEV_NULL = 'NUL'
  120. else:
  121. # Standard Unix uses /dev/null
  122. DEV_NULL = '/dev/null'
  123. ### Platform specific APIs
  124. _libc_search = re.compile(r'(__libc_init)'
  125. '|'
  126. '(GLIBC_([0-9.]+))'
  127. '|'
  128. '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
  129. def libc_ver(executable=sys.executable,lib='',version='',
  130. chunksize=2048):
  131. """ Tries to determine the libc version that the file executable
  132. (which defaults to the Python interpreter) is linked against.
  133. Returns a tuple of strings (lib,version) which default to the
  134. given parameters in case the lookup fails.
  135. Note that the function has intimate knowledge of how different
  136. libc versions add symbols to the executable and thus is probably
  137. only useable for executables compiled using gcc.
  138. The file is read and scanned in chunks of chunksize bytes.
  139. """
  140. if hasattr(os.path, 'realpath'):
  141. # Python 2.2 introduced os.path.realpath(); it is used
  142. # here to work around problems with Cygwin not being
  143. # able to open symlinks for reading
  144. executable = os.path.realpath(executable)
  145. f = open(executable,'rb')
  146. binary = f.read(chunksize)
  147. pos = 0
  148. while 1:
  149. m = _libc_search.search(binary,pos)
  150. if not m:
  151. binary = f.read(chunksize)
  152. if not binary:
  153. break
  154. pos = 0
  155. continue
  156. libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
  157. if libcinit and not lib:
  158. lib = 'libc'
  159. elif glibc:
  160. if lib != 'glibc':
  161. lib = 'glibc'
  162. version = glibcversion
  163. elif glibcversion > version:
  164. version = glibcversion
  165. elif so:
  166. if lib != 'glibc':
  167. lib = 'libc'
  168. if soversion and soversion > version:
  169. version = soversion
  170. if threads and version[-len(threads):] != threads:
  171. version = version + threads
  172. pos = m.end()
  173. f.close()
  174. return lib,version
  175. def _dist_try_harder(distname,version,id):
  176. """ Tries some special tricks to get the distribution
  177. information in case the default method fails.
  178. Currently supports older SuSE Linux, Caldera OpenLinux and
  179. Slackware Linux distributions.
  180. """
  181. if os.path.exists('/var/adm/inst-log/info'):
  182. # SuSE Linux stores distribution information in that file
  183. info = open('/var/adm/inst-log/info').readlines()
  184. distname = 'SuSE'
  185. for line in info:
  186. tv = string.split(line)
  187. if len(tv) == 2:
  188. tag,value = tv
  189. else:
  190. continue
  191. if tag == 'MIN_DIST_VERSION':
  192. version = string.strip(value)
  193. elif tag == 'DIST_IDENT':
  194. values = string.split(value,'-')
  195. id = values[2]
  196. return distname,version,id
  197. if os.path.exists('/etc/.installed'):
  198. # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
  199. info = open('/etc/.installed').readlines()
  200. for line in info:
  201. pkg = string.split(line,'-')
  202. if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
  203. # XXX does Caldera support non Intel platforms ? If yes,
  204. # where can we find the needed id ?
  205. return 'OpenLinux',pkg[1],id
  206. if os.path.isdir('/usr/lib/setup'):
  207. # Check for slackware version tag file (thanks to Greg Andruk)
  208. verfiles = os.listdir('/usr/lib/setup')
  209. for n in range(len(verfiles)-1, -1, -1):
  210. if verfiles[n][:14] != 'slack-version-':
  211. del verfiles[n]
  212. if verfiles:
  213. verfiles.sort()
  214. distname = 'slackware'
  215. version = verfiles[-1][14:]
  216. return distname,version,id
  217. return distname,version,id
  218. _release_filename = re.compile(r'(\w+)[-_](release|version)')
  219. _lsb_release_version = re.compile(r'(.+)'
  220. ' release '
  221. '([\d.]+)'
  222. '[^(]*(?:\((.+)\))?')
  223. _release_version = re.compile(r'([^0-9]+)'
  224. '(?: release )?'
  225. '([\d.]+)'
  226. '[^(]*(?:\((.+)\))?')
  227. # See also http://www.novell.com/coolsolutions/feature/11251.html
  228. # and http://linuxmafia.com/faq/Admin/release-files.html
  229. # and http://data.linux-ntfs.org/rpm/whichrpm
  230. # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
  231. _supported_dists = (
  232. 'SuSE', 'debian', 'fedora', 'redhat', 'centos',
  233. 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
  234. 'UnitedLinux', 'turbolinux')
  235. def _parse_release_file(firstline):
  236. # Default to empty 'version' and 'id' strings. Both defaults are used
  237. # when 'firstline' is empty. 'id' defaults to empty when an id can not
  238. # be deduced.
  239. version = ''
  240. id = ''
  241. # Parse the first line
  242. m = _lsb_release_version.match(firstline)
  243. if m is not None:
  244. # LSB format: "distro release x.x (codename)"
  245. return tuple(m.groups())
  246. # Pre-LSB format: "distro x.x (codename)"
  247. m = _release_version.match(firstline)
  248. if m is not None:
  249. return tuple(m.groups())
  250. # Unknown format... take the first two words
  251. l = string.split(string.strip(firstline))
  252. if l:
  253. version = l[0]
  254. if len(l) > 1:
  255. id = l[1]
  256. return '', version, id
  257. def linux_distribution(distname='', version='', id='',
  258. supported_dists=_supported_dists,
  259. full_distribution_name=1):
  260. """ Tries to determine the name of the Linux OS distribution name.
  261. The function first looks for a distribution release file in
  262. /etc and then reverts to _dist_try_harder() in case no
  263. suitable files are found.
  264. supported_dists may be given to define the set of Linux
  265. distributions to look for. It defaults to a list of currently
  266. supported Linux distributions identified by their release file
  267. name.
  268. If full_distribution_name is true (default), the full
  269. distribution read from the OS is returned. Otherwise the short
  270. name taken from supported_dists is used.
  271. Returns a tuple (distname,version,id) which default to the
  272. args given as parameters.
  273. """
  274. try:
  275. etc = os.listdir('/etc')
  276. except os.error:
  277. # Probably not a Unix system
  278. return distname,version,id
  279. etc.sort()
  280. for file in etc:
  281. m = _release_filename.match(file)
  282. if m is not None:
  283. _distname,dummy = m.groups()
  284. if _distname in supported_dists:
  285. distname = _distname
  286. break
  287. else:
  288. return _dist_try_harder(distname,version,id)
  289. # Read the first line
  290. f = open('/etc/'+file, 'r')
  291. firstline = f.readline()
  292. f.close()
  293. _distname, _version, _id = _parse_release_file(firstline)
  294. if _distname and full_distribution_name:
  295. distname = _distname
  296. if _version:
  297. version = _version
  298. if _id:
  299. id = _id
  300. return distname, version, id
  301. # To maintain backwards compatibility:
  302. def dist(distname='',version='',id='',
  303. supported_dists=_supported_dists):
  304. """ Tries to determine the name of the Linux OS distribution name.
  305. The function first looks for a distribution release file in
  306. /etc and then reverts to _dist_try_harder() in case no
  307. suitable files are found.
  308. Returns a tuple (distname,version,id) which default to the
  309. args given as parameters.
  310. """
  311. return linux_distribution(distname, version, id,
  312. supported_dists=supported_dists,
  313. full_distribution_name=0)
  314. class _popen:
  315. """ Fairly portable (alternative) popen implementation.
  316. This is mostly needed in case os.popen() is not available, or
  317. doesn't work as advertised, e.g. in Win9X GUI programs like
  318. PythonWin or IDLE.
  319. Writing to the pipe is currently not supported.
  320. """
  321. tmpfile = ''
  322. pipe = None
  323. bufsize = None
  324. mode = 'r'
  325. def __init__(self,cmd,mode='r',bufsize=None):
  326. if mode != 'r':
  327. raise ValueError,'popen()-emulation only supports read mode'
  328. import tempfile
  329. self.tmpfile = tmpfile = tempfile.mktemp()
  330. os.system(cmd + ' > %s' % tmpfile)
  331. self.pipe = open(tmpfile,'rb')
  332. self.bufsize = bufsize
  333. self.mode = mode
  334. def read(self):
  335. return self.pipe.read()
  336. def readlines(self):
  337. if self.bufsize is not None:
  338. return self.pipe.readlines()
  339. def close(self,
  340. remove=os.unlink,error=os.error):
  341. if self.pipe:
  342. rc = self.pipe.close()
  343. else:
  344. rc = 255
  345. if self.tmpfile:
  346. try:
  347. remove(self.tmpfile)
  348. except error:
  349. pass
  350. return rc
  351. # Alias
  352. __del__ = close
  353. def popen(cmd, mode='r', bufsize=None):
  354. """ Portable popen() interface.
  355. """
  356. # Find a working popen implementation preferring win32pipe.popen
  357. # over os.popen over _popen
  358. popen = None
  359. if os.environ.get('OS','') == 'Windows_NT':
  360. # On NT win32pipe should work; on Win9x it hangs due to bugs
  361. # in the MS C lib (see MS KnowledgeBase article Q150956)
  362. try:
  363. import win32pipe
  364. except ImportError:
  365. pass
  366. else:
  367. popen = win32pipe.popen
  368. if popen is None:
  369. if hasattr(os,'popen'):
  370. popen = os.popen
  371. # Check whether it works... it doesn't in GUI programs
  372. # on Windows platforms
  373. if sys.platform == 'win32': # XXX Others too ?
  374. try:
  375. popen('')
  376. except os.error:
  377. popen = _popen
  378. else:
  379. popen = _popen
  380. if bufsize is None:
  381. return popen(cmd,mode)
  382. else:
  383. return popen(cmd,mode,bufsize)
  384. def _norm_version(version, build=''):
  385. """ Normalize the version and build strings and return a single
  386. version string using the format major.minor.build (or patchlevel).
  387. """
  388. l = string.split(version,'.')
  389. if build:
  390. l.append(build)
  391. try:
  392. ints = map(int,l)
  393. except ValueError:
  394. strings = l
  395. else:
  396. strings = map(str,ints)
  397. version = string.join(strings[:3],'.')
  398. return version
  399. _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
  400. '.*'
  401. '\[.* ([\d.]+)\])')
  402. # Examples of VER command output:
  403. #
  404. # Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
  405. # Windows XP: Microsoft Windows XP [Version 5.1.2600]
  406. # Windows Vista: Microsoft Windows [Version 6.0.6002]
  407. #
  408. # Note that the "Version" string gets localized on different
  409. # Windows versions.
  410. def _syscmd_ver(system='', release='', version='',
  411. supported_platforms=('win32','win16','dos','os2')):
  412. """ Tries to figure out the OS version used and returns
  413. a tuple (system,release,version).
  414. It uses the "ver" shell command for this which is known
  415. to exists on Windows, DOS and OS/2. XXX Others too ?
  416. In case this fails, the given parameters are used as
  417. defaults.
  418. """
  419. if sys.platform not in supported_platforms:
  420. return system,release,version
  421. # Try some common cmd strings
  422. for cmd in ('ver','command /c ver','cmd /c ver'):
  423. try:
  424. pipe = popen(cmd)
  425. info = pipe.read()
  426. if pipe.close():
  427. raise os.error,'command failed'
  428. # XXX How can I suppress shell errors from being written
  429. # to stderr ?
  430. except os.error,why:
  431. #print 'Command %s failed: %s' % (cmd,why)
  432. continue
  433. except IOError,why:
  434. #print 'Command %s failed: %s' % (cmd,why)
  435. continue
  436. else:
  437. break
  438. else:
  439. return system,release,version
  440. # Parse the output
  441. info = string.strip(info)
  442. m = _ver_output.match(info)
  443. if m is not None:
  444. system,release,version = m.groups()
  445. # Strip trailing dots from version and release
  446. if release[-1] == '.':
  447. release = release[:-1]
  448. if version[-1] == '.':
  449. version = version[:-1]
  450. # Normalize the version and build strings (eliminating additional
  451. # zeros)
  452. version = _norm_version(version)
  453. return system,release,version
  454. _WIN32_CLIENT_RELEASES = {
  455. (5, 0): "2000",
  456. (5, 1): "XP",
  457. # Strictly, 5.2 client is XP 64-bit, but platform.py historically
  458. # has always called it 2003 Server
  459. (5, 2): "2003Server",
  460. (5, None): "post2003",
  461. (6, 0): "Vista",
  462. (6, 1): "7",
  463. (6, 2): "8",
  464. (6, 3): "8.1",
  465. (6, None): "post8.1",
  466. (10, 0): "10",
  467. (10, None): "post10",
  468. }
  469. # Server release name lookup will default to client names if necessary
  470. _WIN32_SERVER_RELEASES = {
  471. (5, 2): "2003Server",
  472. (6, 0): "2008Server",
  473. (6, 1): "2008ServerR2",
  474. (6, 2): "2012Server",
  475. (6, 3): "2012ServerR2",
  476. (6, None): "post2012ServerR2",
  477. }
  478. def _get_real_winver(maj, min, build):
  479. if maj < 6 or (maj == 6 and min < 2):
  480. return maj, min, build
  481. from ctypes import (c_buffer, POINTER, byref, create_unicode_buffer,
  482. Structure, WinDLL, _Pointer)
  483. from ctypes.wintypes import DWORD, HANDLE
  484. class VS_FIXEDFILEINFO(Structure):
  485. _fields_ = [
  486. ("dwSignature", DWORD),
  487. ("dwStrucVersion", DWORD),
  488. ("dwFileVersionMS", DWORD),
  489. ("dwFileVersionLS", DWORD),
  490. ("dwProductVersionMS", DWORD),
  491. ("dwProductVersionLS", DWORD),
  492. ("dwFileFlagsMask", DWORD),
  493. ("dwFileFlags", DWORD),
  494. ("dwFileOS", DWORD),
  495. ("dwFileType", DWORD),
  496. ("dwFileSubtype", DWORD),
  497. ("dwFileDateMS", DWORD),
  498. ("dwFileDateLS", DWORD),
  499. ]
  500. class PVS_FIXEDFILEINFO(_Pointer):
  501. _type_ = VS_FIXEDFILEINFO
  502. kernel32 = WinDLL('kernel32')
  503. version = WinDLL('version')
  504. # We will immediately double the length up to MAX_PATH, but the
  505. # path may be longer, so we retry until the returned string is
  506. # shorter than our buffer.
  507. name_len = actual_len = 130
  508. while actual_len == name_len:
  509. name_len *= 2
  510. name = create_unicode_buffer(name_len)
  511. actual_len = kernel32.GetModuleFileNameW(HANDLE(kernel32._handle),
  512. name, len(name))
  513. if not actual_len:
  514. return maj, min, build
  515. size = version.GetFileVersionInfoSizeW(name, None)
  516. if not size:
  517. return maj, min, build
  518. ver_block = c_buffer(size)
  519. if (not version.GetFileVersionInfoW(name, None, size, ver_block) or
  520. not ver_block):
  521. return maj, min, build
  522. pvi = PVS_FIXEDFILEINFO()
  523. if not version.VerQueryValueW(ver_block, "", byref(pvi), byref(DWORD())):
  524. return maj, min, build
  525. maj = pvi.contents.dwProductVersionMS >> 16
  526. min = pvi.contents.dwProductVersionMS & 0xFFFF
  527. build = pvi.contents.dwProductVersionLS >> 16
  528. return maj, min, build
  529. def win32_ver(release='', version='', csd='', ptype=''):
  530. try:
  531. from sys import getwindowsversion
  532. except ImportError:
  533. return release, version, csd, ptype
  534. try:
  535. from winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
  536. except ImportError:
  537. from _winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
  538. winver = getwindowsversion()
  539. maj, min, build = _get_real_winver(*winver[:3])
  540. version = '{0}.{1}.{2}'.format(maj, min, build)
  541. release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or
  542. _WIN32_CLIENT_RELEASES.get((maj, None)) or
  543. release)
  544. # getwindowsversion() reflect the compatibility mode Python is
  545. # running under, and so the service pack value is only going to be
  546. # valid if the versions match.
  547. if winver[:2] == (maj, min):
  548. try:
  549. csd = 'SP{}'.format(winver.service_pack_major)
  550. except AttributeError:
  551. if csd[:13] == 'Service Pack ':
  552. csd = 'SP' + csd[13:]
  553. # VER_NT_SERVER = 3
  554. if getattr(winver, 'product_type', None) == 3:
  555. release = (_WIN32_SERVER_RELEASES.get((maj, min)) or
  556. _WIN32_SERVER_RELEASES.get((maj, None)) or
  557. release)
  558. key = None
  559. try:
  560. key = OpenKeyEx(HKEY_LOCAL_MACHINE,
  561. r'SOFTWARE\Microsoft\Windows NT\CurrentVersion')
  562. ptype = QueryValueEx(key, 'CurrentType')[0]
  563. except:
  564. pass
  565. finally:
  566. if key:
  567. CloseKey(key)
  568. return release, version, csd, ptype
  569. def _mac_ver_lookup(selectors,default=None):
  570. from gestalt import gestalt
  571. import MacOS
  572. l = []
  573. append = l.append
  574. for selector in selectors:
  575. try:
  576. append(gestalt(selector))
  577. except (RuntimeError, MacOS.Error):
  578. append(default)
  579. return l
  580. def _bcd2str(bcd):
  581. return hex(bcd)[2:]
  582. def _mac_ver_gestalt():
  583. """
  584. Thanks to Mark R. Levinson for mailing documentation links and
  585. code examples for this function. Documentation for the
  586. gestalt() API is available online at:
  587. http://www.rgaros.nl/gestalt/
  588. """
  589. # Check whether the version info module is available
  590. try:
  591. import gestalt
  592. import MacOS
  593. except ImportError:
  594. return None
  595. # Get the infos
  596. sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
  597. # Decode the infos
  598. if sysv:
  599. major = (sysv & 0xFF00) >> 8
  600. minor = (sysv & 0x00F0) >> 4
  601. patch = (sysv & 0x000F)
  602. if (major, minor) >= (10, 4):
  603. # the 'sysv' gestald cannot return patchlevels
  604. # higher than 9. Apple introduced 3 new
  605. # gestalt codes in 10.4 to deal with this
  606. # issue (needed because patch levels can
  607. # run higher than 9, such as 10.4.11)
  608. major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
  609. release = '%i.%i.%i' %(major, minor, patch)
  610. else:
  611. release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
  612. if sysa:
  613. machine = {0x1: '68k',
  614. 0x2: 'PowerPC',
  615. 0xa: 'i386'}.get(sysa,'')
  616. versioninfo=('', '', '')
  617. return release,versioninfo,machine
  618. def _mac_ver_xml():
  619. fn = '/System/Library/CoreServices/SystemVersion.plist'
  620. if not os.path.exists(fn):
  621. return None
  622. try:
  623. import plistlib
  624. except ImportError:
  625. return None
  626. pl = plistlib.readPlist(fn)
  627. release = pl['ProductVersion']
  628. versioninfo=('', '', '')
  629. machine = os.uname()[4]
  630. if machine in ('ppc', 'Power Macintosh'):
  631. # for compatibility with the gestalt based code
  632. machine = 'PowerPC'
  633. return release,versioninfo,machine
  634. def mac_ver(release='',versioninfo=('','',''),machine=''):
  635. """ Get MacOS version information and return it as tuple (release,
  636. versioninfo, machine) with versioninfo being a tuple (version,
  637. dev_stage, non_release_version).
  638. Entries which cannot be determined are set to the parameter values
  639. which default to ''. All tuple entries are strings.
  640. """
  641. # First try reading the information from an XML file which should
  642. # always be present
  643. info = _mac_ver_xml()
  644. if info is not None:
  645. return info
  646. # If that doesn't work for some reason fall back to reading the
  647. # information using gestalt calls.
  648. info = _mac_ver_gestalt()
  649. if info is not None:
  650. return info
  651. # If that also doesn't work return the default values
  652. return release,versioninfo,machine
  653. def _java_getprop(name,default):
  654. from java.lang import System
  655. try:
  656. value = System.getProperty(name)
  657. if value is None:
  658. return default
  659. return value
  660. except AttributeError:
  661. return default
  662. def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
  663. """ Version interface for Jython.
  664. Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  665. a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  666. tuple (os_name,os_version,os_arch).
  667. Values which cannot be determined are set to the defaults
  668. given as parameters (which all default to '').
  669. """
  670. # Import the needed APIs
  671. try:
  672. import java.lang
  673. except ImportError:
  674. return release,vendor,vminfo,osinfo
  675. vendor = _java_getprop('java.vendor', vendor)
  676. release = _java_getprop('java.version', release)
  677. vm_name, vm_release, vm_vendor = vminfo
  678. vm_name = _java_getprop('java.vm.name', vm_name)
  679. vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  680. vm_release = _java_getprop('java.vm.version', vm_release)
  681. vminfo = vm_name, vm_release, vm_vendor
  682. os_name, os_version, os_arch = osinfo
  683. os_arch = _java_getprop('java.os.arch', os_arch)
  684. os_name = _java_getprop('java.os.name', os_name)
  685. os_version = _java_getprop('java.os.version', os_version)
  686. osinfo = os_name, os_version, os_arch
  687. return release, vendor, vminfo, osinfo
  688. ### System name aliasing
  689. def system_alias(system,release,version):
  690. """ Returns (system,release,version) aliased to common
  691. marketing names used for some systems.
  692. It also does some reordering of the information in some cases
  693. where it would otherwise cause confusion.
  694. """
  695. if system == 'Rhapsody':
  696. # Apple's BSD derivative
  697. # XXX How can we determine the marketing release number ?
  698. return 'MacOS X Server',system+release,version
  699. elif system == 'SunOS':
  700. # Sun's OS
  701. if release < '5':
  702. # These releases use the old name SunOS
  703. return system,release,version
  704. # Modify release (marketing release = SunOS release - 3)
  705. l = string.split(release,'.')
  706. if l:
  707. try:
  708. major = int(l[0])
  709. except ValueError:
  710. pass
  711. else:
  712. major = major - 3
  713. l[0] = str(major)
  714. release = string.join(l,'.')
  715. if release < '6':
  716. system = 'Solaris'
  717. else:
  718. # XXX Whatever the new SunOS marketing name is...
  719. system = 'Solaris'
  720. elif system == 'IRIX64':
  721. # IRIX reports IRIX64 on platforms with 64-bit support; yet it
  722. # is really a version and not a different platform, since 32-bit
  723. # apps are also supported..
  724. system = 'IRIX'
  725. if version:
  726. version = version + ' (64bit)'
  727. else:
  728. version = '64bit'
  729. elif system in ('win32','win16'):
  730. # In case one of the other tricks
  731. system = 'Windows'
  732. return system,release,version
  733. ### Various internal helpers
  734. def _platform(*args):
  735. """ Helper to format the platform string in a filename
  736. compatible format e.g. "system-version-machine".
  737. """
  738. # Format the platform string
  739. platform = string.join(
  740. map(string.strip,
  741. filter(len, args)),
  742. '-')
  743. # Cleanup some possible filename obstacles...
  744. replace = string.replace
  745. platform = replace(platform,' ','_')
  746. platform = replace(platform,'/','-')
  747. platform = replace(platform,'\\','-')
  748. platform = replace(platform,':','-')
  749. platform = replace(platform,';','-')
  750. platform = replace(platform,'"','-')
  751. platform = replace(platform,'(','-')
  752. platform = replace(platform,')','-')
  753. # No need to report 'unknown' information...
  754. platform = replace(platform,'unknown','')
  755. # Fold '--'s and remove trailing '-'
  756. while 1:
  757. cleaned = replace(platform,'--','-')
  758. if cleaned == platform:
  759. break
  760. platform = cleaned
  761. while platform[-1] == '-':
  762. platform = platform[:-1]
  763. return platform
  764. def _node(default=''):
  765. """ Helper to determine the node name of this machine.
  766. """
  767. try:
  768. import socket
  769. except ImportError:
  770. # No sockets...
  771. return default
  772. try:
  773. return socket.gethostname()
  774. except socket.error:
  775. # Still not working...
  776. return default
  777. # os.path.abspath is new in Python 1.5.2:
  778. if not hasattr(os.path,'abspath'):
  779. def _abspath(path,
  780. isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
  781. normpath=os.path.normpath):
  782. if not isabs(path):
  783. path = join(getcwd(), path)
  784. return normpath(path)
  785. else:
  786. _abspath = os.path.abspath
  787. def _follow_symlinks(filepath):
  788. """ In case filepath is a symlink, follow it until a
  789. real file is reached.
  790. """
  791. filepath = _abspath(filepath)
  792. while os.path.islink(filepath):
  793. filepath = os.path.normpath(
  794. os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
  795. return filepath
  796. def _syscmd_uname(option,default=''):
  797. """ Interface to the system's uname command.
  798. """
  799. if sys.platform in ('dos','win32','win16','os2'):
  800. # XXX Others too ?
  801. return default
  802. try:
  803. f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
  804. except (AttributeError,os.error):
  805. return default
  806. output = string.strip(f.read())
  807. rc = f.close()
  808. if not output or rc:
  809. return default
  810. else:
  811. return output
  812. def _syscmd_file(target,default=''):
  813. """ Interface to the system's file command.
  814. The function uses the -b option of the file command to have it
  815. ommit the filename in its output and if possible the -L option
  816. to have the command follow symlinks. It returns default in
  817. case the command should fail.
  818. """
  819. # We do the import here to avoid a bootstrap issue.
  820. # See c73b90b6dadd changeset.
  821. #
  822. # [..]
  823. # ranlib libpython2.7.a
  824. # gcc -o python \
  825. # Modules/python.o \
  826. # libpython2.7.a -lsocket -lnsl -ldl -lm
  827. # Traceback (most recent call last):
  828. # File "./setup.py", line 8, in <module>
  829. # from platform import machine as platform_machine
  830. # File "[..]/build/Lib/platform.py", line 116, in <module>
  831. # import sys,string,os,re,subprocess
  832. # File "[..]/build/Lib/subprocess.py", line 429, in <module>
  833. # import select
  834. # ImportError: No module named select
  835. import subprocess
  836. if sys.platform in ('dos','win32','win16','os2'):
  837. # XXX Others too ?
  838. return default
  839. target = _follow_symlinks(target)
  840. try:
  841. proc = subprocess.Popen(['file', target],
  842. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  843. except (AttributeError,os.error):
  844. return default
  845. output = proc.communicate()[0]
  846. rc = proc.wait()
  847. if not output or rc:
  848. return default
  849. else:
  850. return output
  851. ### Information about the used architecture
  852. # Default values for architecture; non-empty strings override the
  853. # defaults given as parameters
  854. _default_architecture = {
  855. 'win32': ('','WindowsPE'),
  856. 'win16': ('','Windows'),
  857. 'dos': ('','MSDOS'),
  858. }
  859. _architecture_split = re.compile(r'[\s,]').split
  860. def architecture(executable=sys.executable,bits='',linkage=''):
  861. """ Queries the given executable (defaults to the Python interpreter
  862. binary) for various architecture information.
  863. Returns a tuple (bits,linkage) which contains information about
  864. the bit architecture and the linkage format used for the
  865. executable. Both values are returned as strings.
  866. Values that cannot be determined are returned as given by the
  867. parameter presets. If bits is given as '', the sizeof(pointer)
  868. (or sizeof(long) on Python version < 1.5.2) is used as
  869. indicator for the supported pointer size.
  870. The function relies on the system's "file" command to do the
  871. actual work. This is available on most if not all Unix
  872. platforms. On some non-Unix platforms where the "file" command
  873. does not exist and the executable is set to the Python interpreter
  874. binary defaults from _default_architecture are used.
  875. """
  876. # Use the sizeof(pointer) as default number of bits if nothing
  877. # else is given as default.
  878. if not bits:
  879. import struct
  880. try:
  881. size = struct.calcsize('P')
  882. except struct.error:
  883. # Older installations can only query longs
  884. size = struct.calcsize('l')
  885. bits = str(size*8) + 'bit'
  886. # Get data from the 'file' system command
  887. if executable:
  888. output = _syscmd_file(executable, '')
  889. else:
  890. output = ''
  891. if not output and \
  892. executable == sys.executable:
  893. # "file" command did not return anything; we'll try to provide
  894. # some sensible defaults then...
  895. if sys.platform in _default_architecture:
  896. b, l = _default_architecture[sys.platform]
  897. if b:
  898. bits = b
  899. if l:
  900. linkage = l
  901. return bits, linkage
  902. # Split the output into a list of strings omitting the filename
  903. fileout = _architecture_split(output)[1:]
  904. if 'executable' not in fileout:
  905. # Format not supported
  906. return bits,linkage
  907. # Bits
  908. if '32-bit' in fileout:
  909. bits = '32bit'
  910. elif 'N32' in fileout:
  911. # On Irix only
  912. bits = 'n32bit'
  913. elif '64-bit' in fileout:
  914. bits = '64bit'
  915. # Linkage
  916. if 'ELF' in fileout:
  917. linkage = 'ELF'
  918. elif 'PE' in fileout:
  919. # E.g. Windows uses this format
  920. if 'Windows' in fileout:
  921. linkage = 'WindowsPE'
  922. else:
  923. linkage = 'PE'
  924. elif 'COFF' in fileout:
  925. linkage = 'COFF'
  926. elif 'MS-DOS' in fileout:
  927. linkage = 'MSDOS'
  928. else:
  929. # XXX the A.OUT format also falls under this class...
  930. pass
  931. return bits,linkage
  932. ### Portable uname() interface
  933. _uname_cache = None
  934. def uname():
  935. """ Fairly portable uname interface. Returns a tuple
  936. of strings (system,node,release,version,machine,processor)
  937. identifying the underlying platform.
  938. Note that unlike the os.uname function this also returns
  939. possible processor information as an additional tuple entry.
  940. Entries which cannot be determined are set to ''.
  941. """
  942. global _uname_cache
  943. no_os_uname = 0
  944. if _uname_cache is not None:
  945. return _uname_cache
  946. processor = ''
  947. # Get some infos from the builtin os.uname API...
  948. try:
  949. system,node,release,version,machine = os.uname()
  950. except AttributeError:
  951. no_os_uname = 1
  952. if no_os_uname or not filter(None, (system, node, release, version, machine)):
  953. # Hmm, no there is either no uname or uname has returned
  954. #'unknowns'... we'll have to poke around the system then.
  955. if no_os_uname:
  956. system = sys.platform
  957. release = ''
  958. version = ''
  959. node = _node()
  960. machine = ''
  961. use_syscmd_ver = 1
  962. # Try win32_ver() on win32 platforms
  963. if system == 'win32':
  964. release,version,csd,ptype = win32_ver()
  965. if release and version:
  966. use_syscmd_ver = 0
  967. # Try to use the PROCESSOR_* environment variables
  968. # available on Win XP and later; see
  969. # http://support.microsoft.com/kb/888731 and
  970. # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  971. if not machine:
  972. # WOW64 processes mask the native architecture
  973. if "PROCESSOR_ARCHITEW6432" in os.environ:
  974. machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
  975. else:
  976. machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  977. if not processor:
  978. processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  979. # Try the 'ver' system command available on some
  980. # platforms
  981. if use_syscmd_ver:
  982. system,release,version = _syscmd_ver(system)
  983. # Normalize system to what win32_ver() normally returns
  984. # (_syscmd_ver() tends to return the vendor name as well)
  985. if system == 'Microsoft Windows':
  986. system = 'Windows'
  987. elif system == 'Microsoft' and release == 'Windows':
  988. # Under Windows Vista and Windows Server 2008,
  989. # Microsoft changed the output of the ver command. The
  990. # release is no longer printed. This causes the
  991. # system and release to be misidentified.
  992. system = 'Windows'
  993. if '6.0' == version[:3]:
  994. release = 'Vista'
  995. else:
  996. release = ''
  997. # In case we still don't know anything useful, we'll try to
  998. # help ourselves
  999. if system in ('win32','win16'):
  1000. if not version:
  1001. if system == 'win32':
  1002. version = '32bit'
  1003. else:
  1004. version = '16bit'
  1005. system = 'Windows'
  1006. elif system[:4] == 'java':
  1007. release,vendor,vminfo,osinfo = java_ver()
  1008. system = 'Java'
  1009. version = string.join(vminfo,', ')
  1010. if not version:
  1011. version = vendor
  1012. # System specific extensions
  1013. if system == 'OpenVMS':
  1014. # OpenVMS seems to have release and version mixed up
  1015. if not release or release == '0':
  1016. release = version
  1017. version = ''
  1018. # Get processor information
  1019. try:
  1020. import vms_lib
  1021. except ImportError:
  1022. pass
  1023. else:
  1024. csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
  1025. if (cpu_number >= 128):
  1026. processor = 'Alpha'
  1027. else:
  1028. processor = 'VAX'
  1029. if not processor:
  1030. # Get processor information from the uname system command
  1031. processor = _syscmd_uname('-p','')
  1032. #If any unknowns still exist, replace them with ''s, which are more portable
  1033. if system == 'unknown':
  1034. system = ''
  1035. if node == 'unknown':
  1036. node = ''
  1037. if release == 'unknown':
  1038. release = ''
  1039. if version == 'unknown':
  1040. version = ''
  1041. if machine == 'unknown':
  1042. machine = ''
  1043. if processor == 'unknown':
  1044. processor = ''
  1045. # normalize name
  1046. if system == 'Microsoft' and release == 'Windows':
  1047. system = 'Windows'
  1048. release = 'Vista'
  1049. _uname_cache = system,node,release,version,machine,processor
  1050. return _uname_cache
  1051. ### Direct interfaces to some of the uname() return values
  1052. def system():
  1053. """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  1054. An empty string is returned if the value cannot be determined.
  1055. """
  1056. return uname()[0]
  1057. def node():
  1058. """ Returns the computer's network name (which may not be fully
  1059. qualified)
  1060. An empty string is returned if the value cannot be determined.
  1061. """
  1062. return uname()[1]
  1063. def release():
  1064. """ Returns the system's release, e.g. '2.2.0' or 'NT'
  1065. An empty string is returned if the value cannot be determined.
  1066. """
  1067. return uname()[2]
  1068. def version():
  1069. """ Returns the system's release version, e.g. '#3 on degas'
  1070. An empty string is returned if the value cannot be determined.
  1071. """
  1072. return uname()[3]
  1073. def machine():
  1074. """ Returns the machine type, e.g. 'i386'
  1075. An empty string is returned if the value cannot be determined.
  1076. """
  1077. return uname()[4]
  1078. def processor():
  1079. """ Returns the (true) processor name, e.g. 'amdk6'
  1080. An empty string is returned if the value cannot be
  1081. determined. Note that many platforms do not provide this
  1082. information or simply return the same value as for machine(),
  1083. e.g. NetBSD does this.
  1084. """
  1085. return uname()[5]
  1086. ### Various APIs for extracting information from sys.version
  1087. _sys_version_parser = re.compile(
  1088. r'([\w.+]+)\s*' # "version<space>"
  1089. r'\(#?([^,]+)' # "(#buildno"
  1090. r'(?:,\s*([\w ]*)' # ", builddate"
  1091. r'(?:,\s*([\w :]*))?)?\)\s*' # ", buildtime)<space>"
  1092. r'\[([^\]]+)\]?') # "[compiler]"
  1093. _ironpython_sys_version_parser = re.compile(
  1094. r'IronPython\s*'
  1095. '([\d\.]+)'
  1096. '(?: \(([\d\.]+)\))?'
  1097. ' on (.NET [\d\.]+)')
  1098. # IronPython covering 2.6 and 2.7
  1099. _ironpython26_sys_version_parser = re.compile(
  1100. r'([\d.]+)\s*'
  1101. '\(IronPython\s*'
  1102. '[\d.]+\s*'
  1103. '\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
  1104. )
  1105. _pypy_sys_version_parser = re.compile(
  1106. r'([\w.+]+)\s*'
  1107. '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  1108. '\[PyPy [^\]]+\]?')
  1109. _sys_version_cache = {}
  1110. def _sys_version(sys_version=None):
  1111. """ Returns a parsed version of Python's sys.version as tuple
  1112. (name, version, branch, revision, buildno, builddate, compiler)
  1113. referring to the Python implementation name, version, branch,
  1114. revision, build number, build date/time as string and the compiler
  1115. identification string.
  1116. Note that unlike the Python sys.version, the returned value
  1117. for the Python version will always include the patchlevel (it
  1118. defaults to '.0').
  1119. The function returns empty strings for tuple entries that
  1120. cannot be determined.
  1121. sys_version may be given to parse an alternative version
  1122. string, e.g. if the version was read from a different Python
  1123. interpreter.
  1124. """
  1125. # Get the Python version
  1126. if sys_version is None:
  1127. sys_version = sys.version
  1128. # Try the cache first
  1129. result = _sys_version_cache.get(sys_version, None)
  1130. if result is not None:
  1131. return result
  1132. # Parse it
  1133. if 'IronPython' in sys_version:
  1134. # IronPython
  1135. name = 'IronPython'
  1136. if sys_version.startswith('IronPython'):
  1137. match = _ironpython_sys_version_parser.match(sys_version)
  1138. else:
  1139. match = _ironpython26_sys_version_parser.match(sys_version)
  1140. if match is None:
  1141. raise ValueError(
  1142. 'failed to parse IronPython sys.version: %s' %
  1143. repr(sys_version))
  1144. version, alt_version, compiler = match.groups()
  1145. buildno = ''
  1146. builddate = ''
  1147. elif sys.platform.startswith('java'):
  1148. # Jython
  1149. name = 'Jython'
  1150. match = _sys_version_parser.match(sys_version)
  1151. if match is None:
  1152. raise ValueError(
  1153. 'failed to parse Jython sys.version: %s' %
  1154. repr(sys_version))
  1155. version, buildno, builddate, buildtime, _ = match.groups()
  1156. if builddate is None:
  1157. builddate = ''
  1158. compiler = sys.platform
  1159. elif "PyPy" in sys_version:
  1160. # PyPy
  1161. name = "PyPy"
  1162. match = _pypy_sys_version_parser.match(sys_version)
  1163. if match is None:
  1164. raise ValueError("failed to parse PyPy sys.version: %s" %
  1165. repr(sys_version))
  1166. version, buildno, builddate, buildtime = match.groups()
  1167. compiler = ""
  1168. else:
  1169. # CPython
  1170. match = _sys_version_parser.match(sys_version)
  1171. if match is None:
  1172. raise ValueError(
  1173. 'failed to parse CPython sys.version: %s' %
  1174. repr(sys_version))
  1175. version, buildno, builddate, buildtime, compiler = \
  1176. match.groups()
  1177. name = 'CPython'
  1178. if builddate is None:
  1179. builddate = ''
  1180. elif buildtime:
  1181. builddate = builddate + ' ' + buildtime
  1182. if hasattr(sys, 'subversion'):
  1183. # sys.subversion was added in Python 2.5
  1184. _, branch, revision = sys.subversion
  1185. else:
  1186. branch = ''
  1187. revision = ''
  1188. # Add the patchlevel version if missing
  1189. l = string.split(version, '.')
  1190. if len(l) == 2:
  1191. l.append('0')
  1192. version = string.join(l, '.')
  1193. # Build and cache the result
  1194. result = (name, version, branch, revision, buildno, builddate, compiler)
  1195. _sys_version_cache[sys_version] = result
  1196. return result
  1197. def python_implementation():
  1198. """ Returns a string identifying the Python implementation.
  1199. Currently, the following implementations are identified:
  1200. 'CPython' (C implementation of Python),
  1201. 'IronPython' (.NET implementation of Python),
  1202. 'Jython' (Java implementation of Python),
  1203. 'PyPy' (Python implementation of Python).
  1204. """
  1205. return _sys_version()[0]
  1206. def python_version():
  1207. """ Returns the Python version as string 'major.minor.patchlevel'
  1208. Note that unlike the Python sys.version, the returned value
  1209. will always include the patchlevel (it defaults to 0).
  1210. """
  1211. return _sys_version()[1]
  1212. def python_version_tuple():
  1213. """ Returns the Python version as tuple (major, minor, patchlevel)
  1214. of strings.
  1215. Note that unlike the Python sys.version, the returned value
  1216. will always include the patchlevel (it defaults to 0).
  1217. """
  1218. return tuple(string.split(_sys_version()[1], '.'))
  1219. def python_branch():
  1220. """ Returns a string identifying the Python implementation
  1221. branch.
  1222. For CPython this is the Subversion branch from which the
  1223. Python binary was built.
  1224. If not available, an empty string is returned.
  1225. """
  1226. return _sys_version()[2]
  1227. def python_revision():
  1228. """ Returns a string identifying the Python implementation
  1229. revision.
  1230. For CPython this is the Subversion revision from which the
  1231. Python binary was built.
  1232. If not available, an empty string is returned.
  1233. """
  1234. return _sys_version()[3]
  1235. def python_build():
  1236. """ Returns a tuple (buildno, builddate) stating the Python
  1237. build number and date as strings.
  1238. """
  1239. return _sys_version()[4:6]
  1240. def python_compiler():
  1241. """ Returns a string identifying the compiler used for compiling
  1242. Python.
  1243. """
  1244. return _sys_version()[6]
  1245. ### The Opus Magnum of platform strings :-)
  1246. _platform_cache = {}
  1247. def platform(aliased=0, terse=0):
  1248. """ Returns a single string identifying the underlying platform
  1249. with as much useful information as possible (but no more :).
  1250. The output is intended to be human readable rather than
  1251. machine parseable. It may look different on different
  1252. platforms and this is intended.
  1253. If "aliased" is true, the function will use aliases for
  1254. various platforms that report system names which differ from
  1255. their common names, e.g. SunOS will be reported as
  1256. Solaris. The system_alias() function is used to implement
  1257. this.
  1258. Setting terse to true causes the function to return only the
  1259. absolute minimum information needed to identify the platform.
  1260. """
  1261. result = _platform_cache.get((aliased, terse), None)
  1262. if result is not None:
  1263. return result
  1264. # Get uname information and then apply platform specific cosmetics
  1265. # to it...
  1266. system,node,release,version,machine,processor = uname()
  1267. if machine == processor:
  1268. processor = ''
  1269. if aliased:
  1270. system,release,version = system_alias(system,release,version)
  1271. if system == 'Windows':
  1272. # MS platforms
  1273. rel,vers,csd,ptype = win32_ver(version)
  1274. if terse:
  1275. platform = _platform(system,release)
  1276. else:
  1277. platform = _platform(system,release,version,csd)
  1278. elif system in ('Linux',):
  1279. # Linux based systems
  1280. distname,distversion,distid = dist('')
  1281. if distname and not terse:
  1282. platform = _platform(system,release,machine,process

Large files files are truncated, but you can click here to view the full file