PageRenderTime 65ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/translator/microbench/pybench/platform.py

https://bitbucket.org/pwaller/pypy
Python | 1217 lines | 1057 code | 49 blank | 111 comment | 62 complexity | 84447790df72d1452463c5ecdd1a0a03 MD5 | raw 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. Note that this module is a fast moving target. I plan to release
  8. version 1.0 as the final version.
  9. Still needed:
  10. - more support for WinCE
  11. - support for MS-DOS (PythonDX ?)
  12. - support for Amiga and other still unsupported platforms running Python
  13. - support for additional Linux distributions
  14. Many thanks to all those who helped adding platform specific
  15. checks (in no particular order):
  16. Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
  17. Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
  18. Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
  19. Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
  20. Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
  21. Colin Kong, Trent Mick
  22. History:
  23. 0.8.0 - added sys.version parser and various new access
  24. APIs (python_version(), python_compiler(), etc.)
  25. 0.7.2 - fixed architecture() to use sizeof(pointer) where available
  26. 0.7.1 - added support for Caldera OpenLinux
  27. 0.7.0 - some fixes for WinCE; untabified the source file
  28. 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
  29. vms_lib.getsyi() configured
  30. 0.6.1 - added code to prevent 'uname -p' on platforms which are
  31. known not to support it
  32. 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
  33. did some cleanup of the interfaces - some APIs have changed
  34. 0.5.5 - fixed another type in the MacOS code... should have
  35. used more coffee today ;-)
  36. 0.5.4 - fixed a few typos in the MacOS code
  37. 0.5.3 - added experimental MacOS support; added better popen()
  38. workarounds in _syscmd_ver() -- still not 100% elegant
  39. though
  40. 0.5.2 - fixed uname() to return '' instead of 'unkown' in all
  41. return values (the system uname command tends to return
  42. 'unkown' instead of just leaving the field emtpy)
  43. 0.5.1 - included code for slackware dist; added exception handlers
  44. to cover up situations where platforms don't have os.popen
  45. (e.g. Mac) or fail on socket.gethostname(); fixed libc
  46. detection RE
  47. 0.5.0 - changed the API names referring to system commands to *syscmd*;
  48. added java_ver(); made syscmd_ver() a private
  49. API (was system_ver() in previous versions) -- use uname()
  50. instead; extended the win32_ver() to also return processor
  51. type information
  52. 0.4.0 - added win32_ver() and modified the platform() output for WinXX
  53. 0.3.4 - fixed a bug in _follow_symlinks()
  54. 0.3.3 - fixed popen() and "file" command invokation bugs
  55. 0.3.2 - added architecture() API and support for it in platform()
  56. 0.3.1 - fixed syscmd_ver() RE to support Windows NT
  57. 0.3.0 - added system alias support
  58. 0.2.3 - removed 'wince' again... oh well.
  59. 0.2.2 - added 'wince' to syscmd_ver() supported platforms
  60. 0.2.1 - added cache logic and changed the platform string format
  61. 0.2.0 - changed the API to use functions instead of module globals
  62. since some action take too long to be run on module import
  63. 0.1.0 - first release
  64. You can always get the latest version of this module at:
  65. http://www.lemburg.com/python/platform.py
  66. If that URL should fail, try contacting the author.
  67. ----------------------------------------------------------------------
  68. Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
  69. Copyright (c) 2000-2001, eGenix.com Software GmbH; mailto:info@egenix.com
  70. Permission to use, copy, modify, and distribute this software and its
  71. documentation for any purpose and without fee or royalty is hereby granted,
  72. provided that the above copyright notice appear in all copies and that
  73. both that copyright notice and this permission notice appear in
  74. supporting documentation or portions thereof, including modifications,
  75. that you make.
  76. THE AUTHOR MARC-ANDRE LEMBURG DISCLAIMS ALL WARRANTIES WITH REGARD TO
  77. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  78. FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
  79. INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  80. FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  81. NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  82. WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
  83. """
  84. __version__ = '0.8.0'
  85. import sys,string,os,re
  86. ### Platform specific APIs
  87. def libc_ver(executable=sys.executable,lib='',version='',
  88. chunksize=2048,
  89. libc_search=re.compile('(__libc_init)'
  90. '|'
  91. '(GLIBC_([0-9.]+))'
  92. '|'
  93. '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)'
  94. )
  95. ):
  96. """ Tries to determine the libc version against which the
  97. file executable (defaults to the Python interpreter) is linked.
  98. Returns a tuple of strings (lib,version) which default to the
  99. given parameters in case the lookup fails.
  100. Note that the function has intimate knowledge of how different
  101. libc versions add symbols to the executable is probably only
  102. useable for executables compiled using gcc.
  103. The file is read and scanned in chunks of chunksize bytes.
  104. """
  105. f = open(executable,'rb')
  106. binary = f.read(chunksize)
  107. pos = 0
  108. while 1:
  109. m = libc_search.search(binary,pos)
  110. if not m:
  111. binary = f.read(chunksize)
  112. if not binary:
  113. break
  114. pos = 0
  115. continue
  116. libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
  117. if libcinit and not lib:
  118. lib = 'libc'
  119. elif glibc:
  120. if lib != 'glibc':
  121. lib = 'glibc'
  122. version = glibcversion
  123. elif glibcversion > version:
  124. version = glibcversion
  125. elif so:
  126. if lib != 'glibc':
  127. lib = 'libc'
  128. if soversion > version:
  129. version = soversion
  130. if threads and version[-len(threads):] != threads:
  131. version = version + threads
  132. pos = m.end()
  133. f.close()
  134. return lib,version
  135. def _dist_try_harder(distname,version,id):
  136. """ Tries some special tricks to get the distribution
  137. information in case the default method fails.
  138. Currently supports older SuSE Linux, Caldera OpenLinux and
  139. Slackware Linux distributions.
  140. """
  141. if os.path.exists('/var/adm/inst-log/info'):
  142. # SuSE Linux stores distribution information in that file
  143. info = open('/var/adm/inst-log/info').readlines()
  144. distname = 'SuSE'
  145. for line in info:
  146. tv = string.split(line)
  147. if len(tv) == 2:
  148. tag,value = tv
  149. else:
  150. continue
  151. if tag == 'MIN_DIST_VERSION':
  152. version = string.strip(value)
  153. elif tag == 'DIST_IDENT':
  154. values = string.split(value,'-')
  155. id = values[2]
  156. return distname,version,id
  157. if os.path.exists('/etc/.installed'):
  158. # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
  159. info = open('/etc/.installed').readlines()
  160. for line in info:
  161. pkg = string.split(line,'-')
  162. if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
  163. # XXX does Caldera support non Intel platforms ? If yes,
  164. # where can we find the needed id ?
  165. return 'OpenLinux',pkg[1],id
  166. if os.path.isdir('/usr/lib/setup'):
  167. # Check for slackware verson tag file (thanks to Greg Andruk)
  168. verfiles = os.listdir('/usr/lib/setup')
  169. for n in range(len(verfiles)-1, -1, -1):
  170. if verfiles[n][:14] != 'slack-version-':
  171. del verfiles[n]
  172. if verfiles:
  173. verfiles.sort()
  174. distname = 'slackware'
  175. version = verfiles[-1][14:]
  176. return distname,version,id
  177. return distname,version,id
  178. def dist(distname='',version='',id='',
  179. supported_dists=('SuSE','debian','redhat','mandrake'),
  180. release_filename=re.compile('(\w+)[-_](release|version)'),
  181. release_version=re.compile('([\d.]+)[^(]*(?:\((.+)\))?')):
  182. """ Tries to determine the name of the OS distribution name
  183. The function first looks for a distribution release file in
  184. /etc and then reverts to _dist_try_harder() in case no
  185. suitable files are found.
  186. Returns a tuple distname,version,id which default to the
  187. args given as parameters.
  188. """
  189. try:
  190. etc = os.listdir('/etc')
  191. except os.error:
  192. # Probably not a Unix system
  193. return distname,version,id
  194. for file in etc:
  195. m = release_filename.match(file)
  196. if m:
  197. _distname,dummy = m.groups()
  198. if _distname in supported_dists:
  199. distname = _distname
  200. break
  201. else:
  202. return _dist_try_harder(distname,version,id)
  203. f = open('/etc/'+file,'r')
  204. firstline = f.readline()
  205. f.close()
  206. m = release_version.search(firstline)
  207. if m:
  208. _version,_id = m.groups()
  209. if _version:
  210. version = _version
  211. if _id:
  212. id = _id
  213. else:
  214. # Unkown format... take the first two words
  215. l = string.split(string.strip(firstline))
  216. if l:
  217. version = l[0]
  218. if len(l) > 1:
  219. id = l[1]
  220. return distname,version,id
  221. class _popen:
  222. """ Fairly portable (alternative) popen implementation.
  223. This is mostly needed in case os.popen() is not available, or
  224. doesn't work as advertised, e.g. in Win9X GUI programs like
  225. PythonWin or IDLE.
  226. XXX Writing to the pipe is currently not supported.
  227. """
  228. tmpfile = ''
  229. pipe = None
  230. bufsize = None
  231. mode = 'r'
  232. def __init__(self,cmd,mode='r',bufsize=None):
  233. if mode != 'r':
  234. raise ValueError('popen()-emulation only supports read mode')
  235. import tempfile
  236. self.tmpfile = tmpfile = tempfile.mktemp()
  237. os.system(cmd + ' > %s' % tmpfile)
  238. self.pipe = open(tmpfile,'rb')
  239. self.bufsize = bufsize
  240. self.mode = mode
  241. def read(self):
  242. return self.pipe.read()
  243. def readlines(self):
  244. if self.bufsize is not None:
  245. return self.pipe.readlines()
  246. def close(self,
  247. remove=os.unlink,error=os.error):
  248. if self.pipe:
  249. rc = self.pipe.close()
  250. else:
  251. rc = 255
  252. if self.tmpfile:
  253. try:
  254. remove(self.tmpfile)
  255. except error:
  256. pass
  257. return rc
  258. # Alias
  259. __del__ = close
  260. def popen(cmd, mode='r', bufsize=None):
  261. """ Portable popen() interface.
  262. """
  263. # Find a working popen implementation preferring win32pipe.popen
  264. # over os.popen over _popen
  265. popen = None
  266. if os.environ.get('OS','') == 'Windows_NT':
  267. # On NT win32pipe should work; on Win9x it hangs due to bugs
  268. # in the MS C lib (see MS KnowledgeBase article Q150956)
  269. try:
  270. import win32pipe
  271. except ImportError:
  272. pass
  273. else:
  274. popen = win32pipe.popen
  275. if popen is None:
  276. if hasattr(os,'popen'):
  277. popen = os.popen
  278. # Check whether it works... it doesn't in GUI programs
  279. # on Windows platforms
  280. if sys.platform == 'win32': # XXX Others too ?
  281. try:
  282. popen('')
  283. except os.error:
  284. popen = _popen
  285. else:
  286. popen = _popen
  287. if bufsize is None:
  288. return popen(cmd,mode)
  289. else:
  290. return popen(cmd,mode,bufsize)
  291. def _norm_version(version,build=''):
  292. """ Normalize the version and build strings and return a sinlge
  293. vesion string using the format major.minor.build (or patchlevel).
  294. """
  295. l = string.split(version,'.')
  296. if build:
  297. l.append(build)
  298. try:
  299. ints = map(int,l)
  300. except ValueError:
  301. strings = l
  302. else:
  303. strings = map(str,ints)
  304. version = string.join(strings[:3],'.')
  305. return version
  306. def _syscmd_ver(system='',release='',version='',
  307. supported_platforms=('win32','win16','dos','os2'),
  308. ver_output=re.compile('(?:([\w ]+) ([\w.]+) '
  309. '.*'
  310. 'Version ([\d.]+))')):
  311. """ Tries to figure out the OS version used and returns
  312. a tuple (system,release,version).
  313. It uses the "ver" shell command for this which is known
  314. to exists on Windows, DOS and OS/2. XXX Others too ?
  315. In case this fails, the given parameters are used as
  316. defaults.
  317. """
  318. if sys.platform not in supported_platforms:
  319. return system,release,version
  320. # Try some common cmd strings
  321. for cmd in ('ver','command /c ver','cmd /c ver'):
  322. try:
  323. pipe = popen(cmd)
  324. info = pipe.read()
  325. if pipe.close():
  326. raise os.error('command failed')
  327. # XXX How can I supress shell errors from being written
  328. # to stderr ?
  329. except os.error,why:
  330. #print 'Command %s failed: %s' % (cmd,why)
  331. continue
  332. except IOError,why:
  333. #print 'Command %s failed: %s' % (cmd,why)
  334. continue
  335. else:
  336. break
  337. else:
  338. return system,release,version
  339. # Parse the output
  340. info = string.strip(info)
  341. m = ver_output.match(info)
  342. if m:
  343. system,release,version = m.groups()
  344. # Strip trailing dots from version and release
  345. if release[-1] == '.':
  346. release = release[:-1]
  347. if version[-1] == '.':
  348. version = version[:-1]
  349. # Normalize the version and build strings (eliminating additional
  350. # zeros)
  351. version = _norm_version(version)
  352. return system,release,version
  353. def _win32_getvalue(key,name,default=''):
  354. """ Read a value for name from the registry key.
  355. In case this fails, default is returned.
  356. """
  357. from win32api import RegQueryValueEx
  358. try:
  359. return RegQueryValueEx(key,name)
  360. except:
  361. return default
  362. def win32_ver(release='',version='',csd='',ptype=''):
  363. """ Get additional version information from the Windows Registry
  364. and return a tuple (version,csd,ptype) referring to version
  365. number, CSD level and OS type (multi/single
  366. processor).
  367. As a hint: ptype returns 'Uniprocessor Free' on single
  368. processor NT machines and 'Multiprocessor Free' on multi
  369. processor machines. The 'Free' refers to the OS version being
  370. free of debugging code. It could also state 'Checked' which
  371. means the OS version uses debugging code, i.e. code that
  372. checks arguments, ranges, etc. (Thomas Heller).
  373. Note: this functions only works if Mark Hammond's win32
  374. package is installed and obviously only runs on Win32
  375. compatible platforms.
  376. XXX Is there any way to find out the processor type on WinXX ?
  377. XXX Is win32 available on Windows CE ?
  378. Adapted from code posted by Karl Putland to comp.lang.python.
  379. """
  380. # Import the needed APIs
  381. try:
  382. import win32api
  383. except ImportError:
  384. return release,version,csd,ptype
  385. from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx
  386. from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\
  387. VER_PLATFORM_WIN32_WINDOWS
  388. # Find out the registry key and some general version infos
  389. maj,min,buildno,plat,csd = GetVersionEx()
  390. version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
  391. if csd[:13] == 'Service Pack ':
  392. csd = 'SP' + csd[13:]
  393. if plat == VER_PLATFORM_WIN32_WINDOWS:
  394. regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
  395. # Try to guess the release name
  396. if maj == 4:
  397. if min == 0:
  398. release = '95'
  399. else:
  400. release = '98'
  401. elif maj == 5:
  402. release = '2000'
  403. elif plat == VER_PLATFORM_WIN32_NT:
  404. regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
  405. if maj <= 4:
  406. release = 'NT'
  407. elif maj == 5:
  408. release = '2000'
  409. else:
  410. if not release:
  411. # E.g. Win3.1 with win32s
  412. release = '%i.%i' % (maj,min)
  413. return release,version,csd,ptype
  414. # Open the registry key
  415. try:
  416. keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey)
  417. # Get a value to make sure the key exists...
  418. RegQueryValueEx(keyCurVer,'SystemRoot')
  419. except:
  420. return release,version,csd,ptype
  421. # Parse values
  422. #subversion = _win32_getvalue(keyCurVer,
  423. # 'SubVersionNumber',
  424. # ('',1))[0]
  425. #if subversion:
  426. # release = release + subversion # 95a, 95b, etc.
  427. build = _win32_getvalue(keyCurVer,
  428. 'CurrentBuildNumber',
  429. ('',1))[0]
  430. ptype = _win32_getvalue(keyCurVer,
  431. 'CurrentType',
  432. (ptype,1))[0]
  433. # Normalize version
  434. version = _norm_version(version,build)
  435. # Close key
  436. RegCloseKey(keyCurVer)
  437. return release,version,csd,ptype
  438. def _mac_ver_lookup(selectors,default=None):
  439. from gestalt import gestalt
  440. l = []
  441. append = l.append
  442. for selector in selectors:
  443. try:
  444. append(gestalt(selector))
  445. except RuntimeError:
  446. append(default)
  447. return l
  448. def _bcd2str(bcd):
  449. return hex(bcd)[2:]
  450. def mac_ver(release='',versioninfo=('','',''),machine=''):
  451. """ Get MacOS version information and return it as tuple (release,
  452. versioninfo, machine) with versioninfo being a tuple (version,
  453. dev_stage, non_release_version).
  454. Entries which cannot be determined are set to ''. All tuple
  455. entries are strings.
  456. Thanks to Mark R. Levinson for mailing documentation links and
  457. code examples for this function. Documentation for the
  458. gestalt() API is available online at:
  459. http://www.rgaros.nl/gestalt/
  460. """
  461. # Check whether the version info module is available
  462. try:
  463. import gestalt
  464. except ImportError:
  465. return release,versioninfo,machine
  466. # Get the infos
  467. sysv,sysu,sysa = _mac_ver_lookup(('sysv','sysu','sysa'))
  468. # Decode the infos
  469. if sysv:
  470. major = (sysv & 0xFF00) >> 8
  471. minor = (sysv & 0x00F0) >> 4
  472. patch = (sysv & 0x000F)
  473. release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
  474. if sysu:
  475. major = (sysu & 0xFF000000) >> 24
  476. minor = (sysu & 0x00F00000) >> 20
  477. bugfix = (sysu & 0x000F0000) >> 16
  478. stage = (sysu & 0x0000FF00) >> 8
  479. nonrel = (sysu & 0x000000FF)
  480. version = '%s.%i.%i' % (_bcd2str(major),minor,bugfix)
  481. nonrel = _bcd2str(nonrel)
  482. stage = {0x20:'development',
  483. 0x40:'alpha',
  484. 0x60:'beta',
  485. 0x80:'final'}.get(stage,'')
  486. versioninfo = (version,stage,nonrel)
  487. if sysa:
  488. machine = {0x1: '68k',
  489. 0x2: 'PowerPC'}.get(sysa,'')
  490. return release,versioninfo,machine
  491. def _java_getprop(self,name,default):
  492. from java.lang import System
  493. try:
  494. return System.getProperty(name)
  495. except:
  496. return default
  497. def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
  498. """ Version interface for JPython.
  499. Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  500. a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  501. tuple (os_name,os_version,os_arch).
  502. Values which cannot be determined are set to the defaults
  503. given as parameters (which all default to '').
  504. """
  505. # Import the needed APIs
  506. try:
  507. import java.lang
  508. except ImportError:
  509. return release,vendor,vminfo,osinfo
  510. vendor = _java_getprop('java.vendor',vendor)
  511. release = _java_getprop('java.version',release)
  512. vm_name,vm_release,vm_vendor = vminfo
  513. vm_name = _java_getprop('java.vm.name',vm_name)
  514. vm_vendor = _java_getprop('java.vm.vendor',vm_vendor)
  515. vm_release = _java_getprop('java.vm.version',vm_release)
  516. vminfo = vm_name,vm_release,vm_vendor
  517. os_name,os_version,os_arch = osinfo
  518. os_arch = _java_getprop('java.os.arch',os_arch)
  519. os_name = _java_getprop('java.os.name',os_name)
  520. os_version = _java_getprop('java.os.version',os_version)
  521. osinfo = os_name,os_version,os_arch
  522. return release,vendor,vminfo,osinfo
  523. ### System name aliasing
  524. def system_alias(system,release,version):
  525. """ Returns (system,release,version) aliased to common
  526. marketing names used for some systems.
  527. It also does some reordering of the information in some cases
  528. where it would otherwise cause confusion.
  529. """
  530. if system == 'Rhapsody':
  531. # Apple's BSD derivative
  532. # XXX How can we determine the marketing release number ?
  533. return 'MacOS X Server',system+release,version
  534. elif system == 'SunOS':
  535. # Sun's OS
  536. if release < '5':
  537. # These releases use the old name SunOS
  538. return system,release,version
  539. # Modify release (marketing release = SunOS release - 3)
  540. l = string.split(release,'.')
  541. if l:
  542. try:
  543. major = int(l[0])
  544. except ValueError:
  545. pass
  546. else:
  547. major = major - 3
  548. l[0] = str(major)
  549. release = string.join(l,'.')
  550. if release < '6':
  551. system = 'Solaris'
  552. else:
  553. # XXX Whatever the new SunOS marketing name is...
  554. system = 'Solaris'
  555. elif system == 'IRIX64':
  556. # IRIX reports IRIX64 on platforms with 64-bit support; yet it
  557. # is really a version and not a different platform, since 32-bit
  558. # apps are also supported..
  559. system = 'IRIX'
  560. if version:
  561. version = version + ' (64bit)'
  562. else:
  563. version = '64bit'
  564. elif system in ('win32','win16'):
  565. # In case one of the other tricks
  566. system = 'Windows'
  567. return system,release,version
  568. ### Various internal helpers
  569. def _platform(*args):
  570. """ Helper to format the platform string in a filename
  571. compatible format e.g. "system-version-machine".
  572. """
  573. # Format the platform string
  574. platform = string.join(
  575. map(string.strip,
  576. filter(len,args)),
  577. '-')
  578. # Cleanup some possible filename obstacles...
  579. replace = string.replace
  580. platform = replace(platform,' ','_')
  581. platform = replace(platform,'/','-')
  582. platform = replace(platform,'\\','-')
  583. platform = replace(platform,':','-')
  584. platform = replace(platform,';','-')
  585. platform = replace(platform,'"','-')
  586. platform = replace(platform,'(','-')
  587. platform = replace(platform,')','-')
  588. # No need to report 'unkown' information...
  589. platform = replace(platform,'unknown','')
  590. # Fold '--'s and remove trailing '-'
  591. while 1:
  592. cleaned = replace(platform,'--','-')
  593. if cleaned == platform:
  594. break
  595. platform = cleaned
  596. while platform[-1] == '-':
  597. platform = platform[:-1]
  598. return platform
  599. def _node(default=''):
  600. """ Helper to determine the node name of this machine.
  601. """
  602. try:
  603. import socket
  604. except ImportError:
  605. # No sockets...
  606. return default
  607. try:
  608. return socket.gethostname()
  609. except socket.error:
  610. # Still not working...
  611. return default
  612. # os.path.abspath is new in Python 1.5.2:
  613. if not hasattr(os.path,'abspath'):
  614. def _abspath(path,
  615. isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
  616. normpath=os.path.normpath):
  617. if not isabs(path):
  618. path = join(getcwd(), path)
  619. return normpath(path)
  620. else:
  621. _abspath = os.path.abspath
  622. def _follow_symlinks(filepath):
  623. """ In case filepath is a symlink, follow it until a
  624. real file is reached.
  625. """
  626. filepath = _abspath(filepath)
  627. while os.path.islink(filepath):
  628. filepath = os.path.normpath(
  629. os.path.join(filepath,os.readlink(filepath)))
  630. return filepath
  631. def _syscmd_uname(option,default=''):
  632. """ Interface to the system's uname command.
  633. """
  634. if sys.platform in ('dos','win32','win16','os2'):
  635. # XXX Others too ?
  636. return default
  637. try:
  638. f = os.popen('uname %s 2> /dev/null' % option)
  639. except (AttributeError,os.error):
  640. return default
  641. output = string.strip(f.read())
  642. rc = f.close()
  643. if not output or rc:
  644. return default
  645. else:
  646. return output
  647. def _syscmd_file(target,default=''):
  648. """ Interface to the system's file command.
  649. The function uses the -b option of the file command to have it
  650. ommit the filename in its output and if possible the -L option
  651. to have the command follow symlinks. It returns default in
  652. case the command should fail.
  653. """
  654. target = _follow_symlinks(target)
  655. try:
  656. f = os.popen('file %s 2> /dev/null' % target)
  657. except (AttributeError,os.error):
  658. return default
  659. output = string.strip(f.read())
  660. rc = f.close()
  661. if not output or rc:
  662. return default
  663. else:
  664. return output
  665. ### Information about the used architecture
  666. # Default values for architecture; non-empty strings override the
  667. # defaults given as parameters
  668. _default_architecture = {
  669. 'win32': ('','WindowsPE'),
  670. 'win16': ('','Windows'),
  671. 'dos': ('','MSDOS'),
  672. }
  673. def architecture(executable=sys.executable,bits='',linkage='',
  674. split=re.compile('[\s,]').split):
  675. """ Queries the given executable (defaults to the Python interpreter
  676. binary) for various architecture informations.
  677. Returns a tuple (bits,linkage) which contain information about
  678. the bit architecture and the linkage format used for the
  679. executable. Both values are returned as strings.
  680. Values that cannot be determined are returned as given by the
  681. parameter presets. If bits is given as '', the sizeof(pointer)
  682. (or sizeof(long) on Python version < 1.5.2) is used as
  683. indicator for the supported pointer size.
  684. The function relies on the system's "file" command to do the
  685. actual work. This is available on most if not all Unix
  686. platforms. On some non-Unix platforms and then only if the
  687. executable points to the Python interpreter defaults from
  688. _default_architecture are used.
  689. """
  690. # Use the sizeof(pointer) as default number of bits if nothing
  691. # else is given as default.
  692. if not bits:
  693. import struct
  694. try:
  695. size = struct.calcsize('P')
  696. except struct.error:
  697. # Older installations can only query longs
  698. size = struct.calcsize('l')
  699. bits = str(size*8) + 'bit'
  700. # Get data from the 'file' system command
  701. output = _syscmd_file(executable,'')
  702. if not output and \
  703. executable == sys.executable:
  704. # "file" command did not return anything; we'll try to provide
  705. # some sensible defaults then...
  706. if _default_architecture.has_key(sys.platform):
  707. b,l = _default_architecture[sys.platform]
  708. if b:
  709. bits = b
  710. if l:
  711. linkage = l
  712. return bits,linkage
  713. # Split the output into a list of strings omitting the filename
  714. fileout = split(output)[1:]
  715. if 'executable' not in fileout:
  716. # Format not supported
  717. return bits,linkage
  718. # Bits
  719. if '32-bit' in fileout:
  720. bits = '32bit'
  721. elif 'N32' in fileout:
  722. # On Irix only
  723. bits = 'n32bit'
  724. elif '64-bit' in fileout:
  725. bits = '64bit'
  726. # Linkage
  727. if 'ELF' in fileout:
  728. linkage = 'ELF'
  729. elif 'PE' in fileout:
  730. # E.g. Windows uses this format
  731. if 'Windows' in fileout:
  732. linkage = 'WindowsPE'
  733. else:
  734. linkage = 'PE'
  735. elif 'COFF' in fileout:
  736. linkage = 'COFF'
  737. elif 'MS-DOS' in fileout:
  738. linkage = 'MSDOS'
  739. else:
  740. # XXX the A.OUT format also falls under this class...
  741. pass
  742. return bits,linkage
  743. ### Portable uname() interface
  744. _uname_cache = None
  745. def uname():
  746. """ Fairly portable uname interface. Returns a tuple
  747. of strings (system,node,release,version,machine,processor)
  748. identifying the underlying platform.
  749. Note that unlike the os.uname function this also returns
  750. possible processor information as additional tuple entry.
  751. Entries which cannot be determined are set to ''.
  752. """
  753. global _uname_cache
  754. if _uname_cache is not None:
  755. return _uname_cache
  756. # Get some infos from the builtin os.uname API...
  757. try:
  758. system,node,release,version,machine = os.uname()
  759. except AttributeError:
  760. # Hmm, no uname... we'll have to poke around the system then.
  761. system = sys.platform
  762. release = ''
  763. version = ''
  764. node = _node()
  765. machine = ''
  766. processor = ''
  767. use_syscmd_ver = 1
  768. # Try win32_ver() on win32 platforms
  769. if system == 'win32':
  770. release,version,csd,ptype = win32_ver()
  771. if release and version:
  772. use_syscmd_ver = 0
  773. # Try the 'ver' system command available on some
  774. # platforms
  775. if use_syscmd_ver:
  776. system,release,version = _syscmd_ver(system)
  777. # In case we still don't know anything useful, we'll try to
  778. # help ourselves
  779. if system in ('win32','win16'):
  780. if not version:
  781. if system == 'win32':
  782. version = '32bit'
  783. else:
  784. version = '16bit'
  785. system = 'Windows'
  786. elif system[:4] == 'java':
  787. release,vendor,vminfo,osinfo = java_ver()
  788. system = 'Java'
  789. version = string.join(vminfo,', ')
  790. if not version:
  791. version = vendor
  792. elif os.name == 'mac':
  793. release,(version,stage,nonrel),machine = mac_ver()
  794. system = 'MacOS'
  795. else:
  796. # System specific extensions
  797. if system == 'OpenVMS':
  798. # OpenVMS seems to have release and version mixed up
  799. if not release or release == '0':
  800. release = version
  801. version = ''
  802. # Get processor information
  803. try:
  804. import vms_lib
  805. except ImportError:
  806. pass
  807. else:
  808. csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
  809. if (cpu_number >= 128):
  810. processor = 'Alpha'
  811. else:
  812. processor = 'VAX'
  813. else:
  814. # Get processor information from the uname system command
  815. processor = _syscmd_uname('-p','')
  816. # 'unkown' is not really any useful as information; we'll convert
  817. # it to '' which is more portable
  818. if system == 'unknown':
  819. system = ''
  820. if node == 'unknown':
  821. node = ''
  822. if release == 'unknown':
  823. release = ''
  824. if version == 'unknown':
  825. version = ''
  826. if machine == 'unknown':
  827. machine = ''
  828. if processor == 'unknown':
  829. processor = ''
  830. _uname_cache = system,node,release,version,machine,processor
  831. return _uname_cache
  832. ### Direct interfaces to some of the uname() return values
  833. def system():
  834. """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  835. An empty string is returned if the value cannot be determined.
  836. """
  837. return uname()[0]
  838. def node():
  839. """ Returns the computer's network name (may not be fully qualified !)
  840. An empty string is returned if the value cannot be determined.
  841. """
  842. return uname()[1]
  843. def release():
  844. """ Returns the system's release, e.g. '2.2.0' or 'NT'
  845. An empty string is returned if the value cannot be determined.
  846. """
  847. return uname()[2]
  848. def version():
  849. """ Returns the system's release version, e.g. '#3 on degas'
  850. An empty string is returned if the value cannot be determined.
  851. """
  852. return uname()[3]
  853. def machine():
  854. """ Returns the machine type, e.g. 'i386'
  855. An empty string is returned if the value cannot be determined.
  856. """
  857. return uname()[4]
  858. def processor():
  859. """ Returns the (true) processor name, e.g. 'amdk6'
  860. An empty string is returned if the value cannot be
  861. determined. Note that many platforms do not provide this
  862. information or simply return the same value as for machine(),
  863. e.g. NetBSD does this.
  864. """
  865. return uname()[5]
  866. ### Various APIs for extracting information from sys.version
  867. _sys_version_parser = re.compile('([\w.+]+)\s*'
  868. '\(#(\d+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  869. '\[([^\]]+)\]?')
  870. _sys_version_cache = None
  871. def _sys_version():
  872. """ Returns a parsed version of Python's sys.version as tuple
  873. (version, buildno, builddate, compiler) referring to the Python
  874. version, build number, build date/time as string and the compiler
  875. identification string.
  876. Note that unlike the Python sys.version, the returned value
  877. for the Python version will always include the patchlevel (it
  878. defaults to '.0').
  879. """
  880. global _sys_version_cache
  881. import sys, re, time
  882. if _sys_version_cache is not None:
  883. return _sys_version_cache
  884. version, buildno, builddate, buildtime, compiler = \
  885. _sys_version_parser.match(sys.version).groups()
  886. buildno = int(buildno)
  887. builddate = builddate + ' ' + buildtime
  888. l = string.split(version, '.')
  889. if len(l) == 2:
  890. l.append('0')
  891. version = string.join(l, '.')
  892. _sys_version_cache = (version, buildno, builddate, compiler)
  893. return _sys_version_cache
  894. def python_version():
  895. """ Returns the Python version as string 'major.minor.patchlevel'
  896. Note that unlike the Python sys.version, the returned value
  897. will always include the patchlevel (it defaults to 0).
  898. """
  899. return _sys_version()[0]
  900. def python_build():
  901. """ Returns a tuple (buildno, buildate) stating the Python
  902. build number and date as strings.
  903. """
  904. return _sys_version()[1:3]
  905. def python_compiler():
  906. """ Returns a string identifying the compiler used for compiling
  907. Python.
  908. """
  909. return _sys_version()[3]
  910. ### The Opus Magnum of platform strings :-)
  911. _platform_cache = None
  912. _platform_aliased_cache = None
  913. def platform(aliased=0, terse=0):
  914. """ Returns a single string identifying the underlying platform
  915. with as much useful information as possible (but no more :).
  916. The output is intended to be human readable rather than
  917. machine parseable. It may look different on different
  918. platforms and this is intended.
  919. If "aliased" is true, the function will use aliases for
  920. various platforms that report system names which differ from
  921. their common names, e.g. SunOS will be reported as
  922. Solaris. The system_alias() function is used to implement
  923. this.
  924. Setting terse to true causes the function to return only the
  925. absolute minimum information needed to identify the platform.
  926. """
  927. global _platform_cache,_platform_aliased_cache
  928. if not aliased and (_platform_cache is not None):
  929. return _platform_cache
  930. elif _platform_aliased_cache is not None:
  931. return _platform_aliased_cache
  932. # Get uname information and then apply platform specific cosmetics
  933. # to it...
  934. system,node,release,version,machine,processor = uname()
  935. if machine == processor:
  936. processor = ''
  937. if aliased:
  938. system,release,version = system_alias(system,release,version)
  939. if system == 'Windows':
  940. # MS platforms
  941. rel,vers,csd,ptype = win32_ver(version)
  942. if terse:
  943. platform = _platform(system,release)
  944. else:
  945. platform = _platform(system,release,version,csd)
  946. elif system in ('Linux',):
  947. # Linux based systems
  948. distname,distversion,distid = dist('')
  949. if distname and not terse:
  950. platform = _platform(system,release,machine,processor,
  951. 'with',
  952. distname,distversion,distid)
  953. else:
  954. # If the distribution name is unknown check for libc vs. glibc
  955. libcname,libcversion = libc_ver(sys.executable)
  956. platform = _platform(system,release,machine,processor,
  957. 'with',
  958. libcname+libcversion)
  959. elif system == 'Java':
  960. # Java platforms
  961. r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
  962. if terse:
  963. platform = _platform(system,release,version)
  964. else:
  965. platform = _platform(system,release,version,
  966. 'on',
  967. os_name,os_version,os_arch)
  968. elif system == 'MacOS':
  969. # MacOS platforms
  970. if terse:
  971. platform = _platform(system,release)
  972. else:
  973. platform = _platform(system,release,machine)
  974. else:
  975. # Generic handler
  976. if terse:
  977. platform = _platform(system,release)
  978. else:
  979. bits,linkage = architecture(sys.executable)
  980. platform = _platform(system,release,machine,processor,bits,linkage)
  981. if aliased:
  982. _platform_aliased_cache = platform
  983. elif terse:
  984. pass
  985. else:
  986. _platform_cache = platform
  987. return platform
  988. if __name__ == '__main__':
  989. # Default is to print the aliased verbose platform string
  990. terse = ('terse' in sys.argv or '--terse' in sys.argv)
  991. aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
  992. print platform(aliased,terse)
  993. sys.exit(0)