PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/platform.py

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