PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/platform.py

https://bitbucket.org/bukzor/pypy
Python | 1614 lines | 1518 code | 4 blank | 92 comment | 2 complexity | 3dbecc8f6039b119610e67ac342434f5 MD5 | raw file

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

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