PageRenderTime 74ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/platform.py

https://bitbucket.org/squeaky/pypy
Python | 1655 lines | 1549 code | 4 blank | 102 comment | 2 complexity | 3f97fe8be7eb58193a603ebe1fe07c04 MD5 | raw file
Possible License(s): Apache-2.0

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 and 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 version 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. # Unknown 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 (service pack), 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. elif min == 2:
  582. if product_type == VER_NT_WORKSTATION:
  583. release = '8'
  584. else:
  585. release = '2012Server'
  586. else:
  587. release = 'post2012Server'
  588. else:
  589. if not release:
  590. # E.g. Win3.1 with win32s
  591. release = '%i.%i' % (maj,min)
  592. return release,version,csd,ptype
  593. # Open the registry key
  594. try:
  595. keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
  596. # Get a value to make sure the key exists...
  597. RegQueryValueEx(keyCurVer, 'SystemRoot')
  598. except:
  599. return release,version,csd,ptype
  600. # Parse values
  601. #subversion = _win32_getvalue(keyCurVer,
  602. # 'SubVersionNumber',
  603. # ('',1))[0]
  604. #if subversion:
  605. # release = release + subversion # 95a, 95b, etc.
  606. build = _win32_getvalue(keyCurVer,
  607. 'CurrentBuildNumber',
  608. ('',1))[0]
  609. ptype = _win32_getvalue(keyCurVer,
  610. 'CurrentType',
  611. (ptype,1))[0]
  612. # Normalize version
  613. version = _norm_version(version,build)
  614. # Close key
  615. RegCloseKey(keyCurVer)
  616. return release,version,csd,ptype
  617. def _mac_ver_lookup(selectors,default=None):
  618. from gestalt import gestalt
  619. import MacOS
  620. l = []
  621. append = l.append
  622. for selector in selectors:
  623. try:
  624. append(gestalt(selector))
  625. except (RuntimeError, MacOS.Error):
  626. append(default)
  627. return l
  628. def _bcd2str(bcd):
  629. return hex(bcd)[2:]
  630. def _mac_ver_gestalt():
  631. """
  632. Thanks to Mark R. Levinson for mailing documentation links and
  633. code examples for this function. Documentation for the
  634. gestalt() API is available online at:
  635. http://www.rgaros.nl/gestalt/
  636. """
  637. # Check whether the version info module is available
  638. try:
  639. import gestalt
  640. import MacOS
  641. except ImportError:
  642. return None
  643. # Get the infos
  644. sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
  645. # Decode the infos
  646. if sysv:
  647. major = (sysv & 0xFF00) >> 8
  648. minor = (sysv & 0x00F0) >> 4
  649. patch = (sysv & 0x000F)
  650. if (major, minor) >= (10, 4):
  651. # the 'sysv' gestald cannot return patchlevels
  652. # higher than 9. Apple introduced 3 new
  653. # gestalt codes in 10.4 to deal with this
  654. # issue (needed because patch levels can
  655. # run higher than 9, such as 10.4.11)
  656. major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
  657. release = '%i.%i.%i' %(major, minor, patch)
  658. else:
  659. release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
  660. if sysa:
  661. machine = {0x1: '68k',
  662. 0x2: 'PowerPC',
  663. 0xa: 'i386'}.get(sysa,'')
  664. versioninfo=('', '', '')
  665. return release,versioninfo,machine
  666. def _mac_ver_xml():
  667. fn = '/System/Library/CoreServices/SystemVersion.plist'
  668. if not os.path.exists(fn):
  669. return None
  670. try:
  671. import plistlib
  672. except ImportError:
  673. return None
  674. pl = plistlib.readPlist(fn)
  675. release = pl['ProductVersion']
  676. versioninfo=('', '', '')
  677. machine = os.uname()[4]
  678. if machine in ('ppc', 'Power Macintosh'):
  679. # for compatibility with the gestalt based code
  680. machine = 'PowerPC'
  681. return release,versioninfo,machine
  682. def mac_ver(release='',versioninfo=('','',''),machine=''):
  683. """ Get MacOS version information and return it as tuple (release,
  684. versioninfo, machine) with versioninfo being a tuple (version,
  685. dev_stage, non_release_version).
  686. Entries which cannot be determined are set to the parameter values
  687. which default to ''. All tuple entries are strings.
  688. """
  689. # First try reading the information from an XML file which should
  690. # always be present
  691. info = _mac_ver_xml()
  692. if info is not None:
  693. return info
  694. # If that doesn't work for some reason fall back to reading the
  695. # information using gestalt calls.
  696. info = _mac_ver_gestalt()
  697. if info is not None:
  698. return info
  699. # If that also doesn't work return the default values
  700. return release,versioninfo,machine
  701. def _java_getprop(name,default):
  702. from java.lang import System
  703. try:
  704. value = System.getProperty(name)
  705. if value is None:
  706. return default
  707. return value
  708. except AttributeError:
  709. return default
  710. def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
  711. """ Version interface for Jython.
  712. Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  713. a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  714. tuple (os_name,os_version,os_arch).
  715. Values which cannot be determined are set to the defaults
  716. given as parameters (which all default to '').
  717. """
  718. # Import the needed APIs
  719. try:
  720. import java.lang
  721. except ImportError:
  722. return release,vendor,vminfo,osinfo
  723. vendor = _java_getprop('java.vendor', vendor)
  724. release = _java_getprop('java.version', release)
  725. vm_name, vm_release, vm_vendor = vminfo
  726. vm_name = _java_getprop('java.vm.name', vm_name)
  727. vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  728. vm_release = _java_getprop('java.vm.version', vm_release)
  729. vminfo = vm_name, vm_release, vm_vendor
  730. os_name, os_version, os_arch = osinfo
  731. os_arch = _java_getprop('java.os.arch', os_arch)
  732. os_name = _java_getprop('java.os.name', os_name)
  733. os_version = _java_getprop('java.os.version', os_version)
  734. osinfo = os_name, os_version, os_arch
  735. return release, vendor, vminfo, osinfo
  736. ### System name aliasing
  737. def system_alias(system,release,version):
  738. """ Returns (system,release,version) aliased to common
  739. marketing names used for some systems.
  740. It also does some reordering of the information in some cases
  741. where it would otherwise cause confusion.
  742. """
  743. if system == 'Rhapsody':
  744. # Apple's BSD derivative
  745. # XXX How can we determine the marketing release number ?
  746. return 'MacOS X Server',system+release,version
  747. elif system == 'SunOS':
  748. # Sun's OS
  749. if release < '5':
  750. # These releases use the old name SunOS
  751. return system,release,version
  752. # Modify release (marketing release = SunOS release - 3)
  753. l = string.split(release,'.')
  754. if l:
  755. try:
  756. major = int(l[0])
  757. except ValueError:
  758. pass
  759. else:
  760. major = major - 3
  761. l[0] = str(major)
  762. release = string.join(l,'.')
  763. if release < '6':
  764. system = 'Solaris'
  765. else:
  766. # XXX Whatever the new SunOS marketing name is...
  767. system = 'Solaris'
  768. elif system == 'IRIX64':
  769. # IRIX reports IRIX64 on platforms with 64-bit support; yet it
  770. # is really a version and not a different platform, since 32-bit
  771. # apps are also supported..
  772. system = 'IRIX'
  773. if version:
  774. version = version + ' (64bit)'
  775. else:
  776. version = '64bit'
  777. elif system in ('win32','win16'):
  778. # In case one of the other tricks
  779. system = 'Windows'
  780. return system,release,version
  781. ### Various internal helpers
  782. def _platform(*args):
  783. """ Helper to format the platform string in a filename
  784. compatible format e.g. "system-version-machine".
  785. """
  786. # Format the platform string
  787. platform = string.join(
  788. map(string.strip,
  789. filter(len, args)),
  790. '-')
  791. # Cleanup some possible filename obstacles...
  792. replace = string.replace
  793. platform = replace(platform,' ','_')
  794. platform = replace(platform,'/','-')
  795. platform = replace(platform,'\\','-')
  796. platform = replace(platform,':','-')
  797. platform = replace(platform,';','-')
  798. platform = replace(platform,'"','-')
  799. platform = replace(platform,'(','-')
  800. platform = replace(platform,')','-')
  801. # No need to report 'unknown' information...
  802. platform = replace(platform,'unknown','')
  803. # Fold '--'s and remove trailing '-'
  804. while 1:
  805. cleaned = replace(platform,'--','-')
  806. if cleaned == platform:
  807. break
  808. platform = cleaned
  809. while platform[-1] == '-':
  810. platform = platform[:-1]
  811. return platform
  812. def _node(default=''):
  813. """ Helper to determine the node name of this machine.
  814. """
  815. try:
  816. import socket
  817. except ImportError:
  818. # No sockets...
  819. return default
  820. try:
  821. return socket.gethostname()
  822. except socket.error:
  823. # Still not working...
  824. return default
  825. # os.path.abspath is new in Python 1.5.2:
  826. if not hasattr(os.path,'abspath'):
  827. def _abspath(path,
  828. isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
  829. normpath=os.path.normpath):
  830. if not isabs(path):
  831. path = join(getcwd(), path)
  832. return normpath(path)
  833. else:
  834. _abspath = os.path.abspath
  835. def _follow_symlinks(filepath):
  836. """ In case filepath is a symlink, follow it until a
  837. real file is reached.
  838. """
  839. filepath = _abspath(filepath)
  840. while os.path.islink(filepath):
  841. filepath = os.path.normpath(
  842. os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
  843. return filepath
  844. def _syscmd_uname(option,default=''):
  845. """ Interface to the system's uname command.
  846. """
  847. if sys.platform in ('dos','win32','win16','os2'):
  848. # XXX Others too ?
  849. return default
  850. try:
  851. f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
  852. except (AttributeError,os.error):
  853. return default
  854. output = string.strip(f.read())
  855. rc = f.close()
  856. if not output or rc:
  857. return default
  858. else:
  859. return output
  860. def _syscmd_file(target,default=''):
  861. """ Interface to the system's file command.
  862. The function uses the -b option of the file command to have it
  863. ommit the filename in its output and if possible the -L option
  864. to have the command follow symlinks. It returns default in
  865. case the command should fail.
  866. """
  867. # We do the import here to avoid a bootstrap issue.
  868. # See c73b90b6dadd changeset.
  869. #
  870. # [..]
  871. # ranlib libpython2.7.a
  872. # gcc -o python \
  873. # Modules/python.o \
  874. # libpython2.7.a -lsocket -lnsl -ldl -lm
  875. # Traceback (most recent call last):
  876. # File "./setup.py", line 8, in <module>
  877. # from platform import machine as platform_machine
  878. # File "[..]/build/Lib/platform.py", line 116, in <module>
  879. # import sys,string,os,re,subprocess
  880. # File "[..]/build/Lib/subprocess.py", line 429, in <module>
  881. # import select
  882. # ImportError: No module named select
  883. import subprocess
  884. if sys.platform in ('dos','win32','win16','os2'):
  885. # XXX Others too ?
  886. return default
  887. target = _follow_symlinks(target)
  888. try:
  889. proc = subprocess.Popen(['file', target],
  890. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  891. except (AttributeError,os.error):
  892. return default
  893. output = proc.communicate()[0]
  894. rc = proc.wait()
  895. if not output or rc:
  896. return default
  897. else:
  898. return output
  899. ### Information about the used architecture
  900. # Default values for architecture; non-empty strings override the
  901. # defaults given as parameters
  902. _default_architecture = {
  903. 'win32': ('','WindowsPE'),
  904. 'win16': ('','Windows'),
  905. 'dos': ('','MSDOS'),
  906. }
  907. _architecture_split = re.compile(r'[\s,]').split
  908. def architecture(executable=sys.executable,bits='',linkage=''):
  909. """ Queries the given executable (defaults to the Python interpreter
  910. binary) for various architecture information.
  911. Returns a tuple (bits,linkage) which contains information about
  912. the bit architecture and the linkage format used for the
  913. executable. Both values are returned as strings.
  914. Values that cannot be determined are returned as given by the
  915. parameter presets. If bits is given as '', the sizeof(pointer)
  916. (or sizeof(long) on Python version < 1.5.2) is used as
  917. indicator for the supported pointer size.
  918. The function relies on the system's "file" command to do the
  919. actual work. This is available on most if not all Unix
  920. platforms. On some non-Unix platforms where the "file" command
  921. does not exist and the executable is set to the Python interpreter
  922. binary defaults from _default_architecture are used.
  923. """
  924. # Use the sizeof(pointer) as default number of bits if nothing
  925. # else is given as default.
  926. if not bits:
  927. import struct
  928. try:
  929. size = struct.calcsize('P')
  930. except struct.error:
  931. # Older installations can only query longs
  932. size = struct.calcsize('l')
  933. bits = str(size*8) + 'bit'
  934. # Get data from the 'file' system command
  935. if executable:
  936. output = _syscmd_file(executable, '')
  937. else:
  938. output = ''
  939. if not output and \
  940. executable == sys.executable:
  941. # "file" command did not return anything; we'll try to provide
  942. # some sensible defaults then...
  943. if sys.platform in _default_architecture:
  944. b, l = _default_architecture[sys.platform]
  945. if b:
  946. bits = b
  947. if l:
  948. linkage = l
  949. return bits, linkage
  950. # Split the output into a list of strings omitting the filename
  951. fileout = _architecture_split(output)[1:]
  952. if 'executable' not in fileout:
  953. # Format not supported
  954. return bits,linkage
  955. # Bits
  956. if '32-bit' in fileout:
  957. bits = '32bit'
  958. elif 'N32' in fileout:
  959. # On Irix only
  960. bits = 'n32bit'
  961. elif '64-bit' in fileout:
  962. bits = '64bit'
  963. # Linkage
  964. if 'ELF' in fileout:
  965. linkage = 'ELF'
  966. elif 'PE' in fileout:
  967. # E.g. Windows uses this format
  968. if 'Windows' in fileout:
  969. linkage = 'WindowsPE'
  970. else:
  971. linkage = 'PE'
  972. elif 'COFF' in fileout:
  973. linkage = 'COFF'
  974. elif 'MS-DOS' in fileout:
  975. linkage = 'MSDOS'
  976. else:
  977. # XXX the A.OUT format also falls under this class...
  978. pass
  979. return bits,linkage
  980. ### Portable uname() interface
  981. _uname_cache = None
  982. def uname():
  983. """ Fairly portable uname interface. Returns a tuple
  984. of strings (system,node,release,version,machine,processor)
  985. identifying the underlying platform.
  986. Note that unlike the os.uname function this also returns
  987. possible processor information as an additional tuple entry.
  988. Entries which cannot be determined are set to ''.
  989. """
  990. global _uname_cache
  991. no_os_uname = 0
  992. if _uname_cache is not None:
  993. return _uname_cache
  994. processor = ''
  995. # Get some infos from the builtin os.uname API...
  996. try:
  997. system,node,release,version,machine = os.uname()
  998. except AttributeError:
  999. no_os_uname = 1
  1000. if no_os_uname or not filter(None, (system, node, release, version, machine)):
  1001. # Hmm, no there is either no uname or uname has returned
  1002. #'unknowns'... we'll have to poke around the system then.
  1003. if no_os_uname:
  1004. system = sys.platform
  1005. release = ''
  1006. version = ''
  1007. node = _node()
  1008. machine = ''
  1009. use_syscmd_ver = 1
  1010. # Try win32_ver() on win32 platforms
  1011. if system == 'win32':
  1012. release,version,csd,ptype = win32_ver()
  1013. if release and version:
  1014. use_syscmd_ver = 0
  1015. # Try to use the PROCESSOR_* environment variables
  1016. # available on Win XP and later; see
  1017. # http://support.microsoft.com/kb/888731 and
  1018. # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  1019. if not machine:
  1020. # WOW64 processes mask the native architecture
  1021. if "PROCESSOR_ARCHITEW6432" in os.environ:
  1022. machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
  1023. else:
  1024. machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  1025. if not processor:
  1026. processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  1027. # Try the 'ver' system command available on some
  1028. # platforms
  1029. if use_syscmd_ver:
  1030. system,release,version = _syscmd_ver(system)
  1031. # Normalize system to what win32_ver() normally returns
  1032. # (_syscmd_ver() tends to return the vendor name as well)
  1033. if system == 'Microsoft Windows':
  1034. system = 'Windows'
  1035. elif system == 'Microsoft' and release == 'Windows':
  1036. # Under Windows Vista and Windows Server 2008,
  1037. # Microsoft changed the output of the ver command. The
  1038. # release is no longer printed. This causes the
  1039. # system and release to be misidentified.
  1040. system = 'Windows'
  1041. if '6.0' == version[:3]:
  1042. release = 'Vista'
  1043. else:
  1044. release = ''
  1045. # In case we still don't know anything useful, we'll try to
  1046. # help ourselves
  1047. if system in ('win32','win16'):
  1048. if not version:
  1049. if system == 'win32':
  1050. version = '32bit'
  1051. else:
  1052. version = '16bit'
  1053. system = 'Windows'
  1054. elif system[:4] == 'java':
  1055. release,vendor,vminfo,osinfo = java_ver()
  1056. system = 'Java'
  1057. version = string.join(vminfo,', ')
  1058. if not version:
  1059. version = vendor
  1060. # System specific extensions
  1061. if system == 'OpenVMS':
  1062. # OpenVMS seems to have release and version mixed up
  1063. if not release or release == '0':
  1064. release = version
  1065. version = ''
  1066. # Get processor information
  1067. try:
  1068. import vms_lib
  1069. except ImportError:
  1070. pass
  1071. else:
  1072. csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
  1073. if (cpu_number >= 128):
  1074. processor = 'Alpha'
  1075. else:
  1076. processor = 'VAX'
  1077. if not processor:
  1078. # Get processor information from the uname system command
  1079. processor = _syscmd_uname('-p','')
  1080. #If any unknowns still exist, replace them with ''s, which are more portable
  1081. if system == 'unknown':
  1082. system = ''
  1083. if node == 'unknown':
  1084. node = ''
  1085. if release == 'unknown':
  1086. release = ''
  1087. if version == 'unknown':
  1088. version = ''
  1089. if machine == 'unknown':
  1090. machine = ''
  1091. if processor == 'unknown':
  1092. processor = ''
  1093. # normalize name
  1094. if system == 'Microsoft' and release == 'Windows':
  1095. system = 'Windows'
  1096. release = 'Vista'
  1097. _uname_cache = system,node,release,version,machine,processor
  1098. return _uname_cache
  1099. ### Direct interfaces to some of the uname() return values
  1100. def system():
  1101. """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  1102. An empty string is returned if the value cannot be determined.
  1103. """
  1104. return uname()[0]
  1105. def node():
  1106. """ Returns the computer's network name (which may not be fully
  1107. qualified)
  1108. An empty string is returned if the value cannot be determined.
  1109. """
  1110. return uname()[1]
  1111. def release():
  1112. """ Returns the system's release, e.g. '2.2.0' or 'NT'
  1113. An empty string is returned if the value cannot be determined.
  1114. """
  1115. return uname()[2]
  1116. def version():
  1117. """ Returns the system's release version, e.g. '#3 on degas'
  1118. An empty string is returned if the value cannot be determined.
  1119. """
  1120. return uname()[3]
  1121. def machine():
  1122. """ Returns the machine type, e.g. 'i386'
  1123. An empty string is returned if the value cannot be determined.
  1124. """
  1125. return uname()[4]
  1126. def processor():
  1127. """ Returns the (true) processor name, e.g. 'amdk6'
  1128. An empty string is returned if the value cannot be
  1129. determined. Note that many platforms do not provide this
  1130. information or simply return the same value as for machine(),
  1131. e.g. NetBSD does this.
  1132. """
  1133. return uname()[5]
  1134. ### Various APIs for extracting information from sys.version
  1135. _sys_version_parser = re.compile(
  1136. r'([\w.+]+)\s*'
  1137. '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  1138. '\[([^\]]+)\]?')
  1139. _ironpython_sys_version_parser = re.compile(
  1140. r'IronPython\s*'
  1141. '([\d\.]+)'
  1142. '(?: \(([\d\.]+)\))?'
  1143. ' on (.NET [\d\.]+)')
  1144. # IronPython covering 2.6 and 2.7
  1145. _ironpython26_sys_version_parser = re.compile(
  1146. r'([\d.]+)\s*'
  1147. '\(IronPython\s*'
  1148. '[\d.]+\s*'
  1149. '\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
  1150. )
  1151. _pypy_sys_version_parser = re.compile(
  1152. r'([\w.+]+)\s*'
  1153. '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  1154. '\[PyPy [^\]]+\]?')
  1155. _sys_version_cache = {}
  1156. def _sys_version(sys_version=None):
  1157. """ Returns a parsed version of Python's sys.version as tuple
  1158. (name, version, branch, revision, buildno, builddate, compiler)
  1159. referring to the Python implementation name, version, branch,
  1160. revision, build number, build date/time as string and the compiler
  1161. identification string.
  1162. Note that unlike the Python sys.version, the returned value
  1163. for the Python version will always include the patchlevel (it
  1164. defaults to '.0').
  1165. The function returns empty strings for tuple entries that
  1166. cannot be determined.
  1167. sys_version may be given to parse an alternative version
  1168. string, e.g. if the version was read from a different Python
  1169. interpreter.
  1170. """
  1171. # Get the Python version
  1172. if sys_version is None:
  1173. sys_version = sys.version
  1174. # Try the cache first
  1175. result = _sys_version_cache.get(sys_version, None)
  1176. if result is not None:
  1177. return result
  1178. # Parse it
  1179. if 'IronPython' in sys_version:
  1180. # IronPython
  1181. name = 'IronPython'
  1182. if sys_version.startswith('IronPython'):
  1183. match = _ironpython_sys_version_parser.match(sys_version)
  1184. else:
  1185. match = _ironpython26_sys_version_parser.match(sys_version)
  1186. if match is None:
  1187. raise ValueError(
  1188. 'failed to parse IronPython sys.version: %s' %
  1189. repr(sys_version))
  1190. version, alt_version, compiler = match.groups()
  1191. buildno = ''
  1192. builddate = ''
  1193. elif sys.platform.startswith('java'):
  1194. # Jython
  1195. name = 'Jython'
  1196. match = _sys_version_parser.match(sys_version)
  1197. if match is None:
  1198. raise ValueError(
  1199. 'failed to parse Jython sys.version: %s' %
  1200. repr(sys_version))
  1201. version, buildno, builddate, buildtime, _ = match.groups()
  1202. compiler = sys.platform
  1203. elif "PyPy" in sys_version:
  1204. # PyPy
  1205. name = "PyPy"
  1206. match = _pypy_sys_version_parser.match(sys_version)
  1207. if match is None:
  1208. raise ValueError("failed to parse PyPy sys.version: %s" %
  1209. repr(sys_version))
  1210. version, buildno, builddate, buildtime = match.groups()
  1211. compiler = ""
  1212. else:
  1213. # CPython
  1214. match = _sys_version_parser.match(sys_version)
  1215. if match is None:
  1216. raise ValueError(
  1217. 'failed to parse CPython sys.version: %s' %
  1218. repr(sys_version))
  1219. version, buildno, builddate, buildtime, compiler = \
  1220. match.groups()
  1221. name = 'CPython'
  1222. builddate = builddate + ' ' + buildtime
  1223. if hasattr(sys, 'subversion'):
  1224. # sys.subversion was added in Python 2.5
  1225. _, branch, revision = sys.subversion
  1226. else:
  1227. branch = ''
  1228. revision = ''
  1229. # Add the patchlevel version if missing
  1230. l = string.split(version, '.')
  1231. if len(l) == 2:
  1232. l.append('0')
  1233. version = string.join(l, '.')
  1234. # Build and cache the result
  1235. result = (name, version, branch, revision, buildno, builddate, compiler)
  1236. _sys_version_cache[sys_version] = result
  1237. return result
  1238. def python_implementation():
  1239. """ Returns a string identifying the Python implementation.
  1240. Currently, the following implementations are identified:
  1241. 'CPython' (C implementation of Python),
  1242. 'IronPython' (.NET implementation of Python),
  1243. 'Jython' (Java implementation of Python),
  1244. 'PyPy' (Python implementation of Python).
  1245. """
  1246. return _sys_version()[0]
  1247. def python_version():
  1248. """ Returns the Python version as string 'major.minor.patchlevel'
  1249. Note that unlike the Python sys.version, the returned value
  1250. will always include the patchlevel (it defaults to 0).
  1251. """
  1252. return _sys_version()[1]
  1253. def python_version_tuple():
  1254. """ Returns the Python version as tuple (major, minor, patchlevel)
  1255. of strings.
  1256. Note that unlike the Python sys.version, the returned value
  1257. will always include the patchlevel (it defaults to 0).
  1258. """
  1259. return tuple(string.split(_sys_version()[1], '.'))
  1260. def python_branch():
  1261. """ Returns a string identifying the Python implementation
  1262. branch.
  1263. For CPython this is the Subversion branch from which the
  1264. Python binary was built.
  1265. If not available, an empty string is returned.
  1266. """
  1267. return _sys_version()[2]
  1268. def python_revision():
  1269. """ Returns a string identifying the Python implementation
  1270. revision.
  1271. For CPython this is the Subversion revision from which the
  1272. Python binary was built.
  1273. If not available, an empty string is returned.
  1274. """
  1275. return _sys_version()[3]
  1276. def python_build():
  1277. """ Returns a tuple (b…

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