Added new optional credentials argument to SMTPHandler.__init__, and smtp.login(...
[python.git] / Lib / platform.py
blobca4b86c964d5983f4e666335a6e5115270ed6109
1 #!/usr/bin/env python
3 """ This module tries to retrieve as much platform-identifying data as
4 possible. It makes this information available via function APIs.
6 If called from the command line, it prints the platform
7 information concatenated as single string to stdout. The output
8 format is useable as part of a filename.
10 """
11 # This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
12 # If you find problems, please submit bug reports/patches via the
13 # Python SourceForge Project Page and assign them to "lemburg".
15 # Note: Please keep this module compatible to Python 1.5.2.
17 # Still needed:
18 # * more support for WinCE
19 # * support for MS-DOS (PythonDX ?)
20 # * support for Amiga and other still unsupported platforms running Python
21 # * support for additional Linux distributions
23 # Many thanks to all those who helped adding platform-specific
24 # checks (in no particular order):
26 # Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
27 # Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
28 # Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
29 # Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
30 # Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
31 # Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
33 # History:
35 # <see CVS and SVN checkin messages for history>
37 # 1.0.6 - added linux_distribution()
38 # 1.0.5 - fixed Java support to allow running the module on Jython
39 # 1.0.4 - added IronPython support
40 # 1.0.3 - added normalization of Windows system name
41 # 1.0.2 - added more Windows support
42 # 1.0.1 - reformatted to make doc.py happy
43 # 1.0.0 - reformatted a bit and checked into Python CVS
44 # 0.8.0 - added sys.version parser and various new access
45 # APIs (python_version(), python_compiler(), etc.)
46 # 0.7.2 - fixed architecture() to use sizeof(pointer) where available
47 # 0.7.1 - added support for Caldera OpenLinux
48 # 0.7.0 - some fixes for WinCE; untabified the source file
49 # 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
50 # vms_lib.getsyi() configured
51 # 0.6.1 - added code to prevent 'uname -p' on platforms which are
52 # known not to support it
53 # 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
54 # did some cleanup of the interfaces - some APIs have changed
55 # 0.5.5 - fixed another type in the MacOS code... should have
56 # used more coffee today ;-)
57 # 0.5.4 - fixed a few typos in the MacOS code
58 # 0.5.3 - added experimental MacOS support; added better popen()
59 # workarounds in _syscmd_ver() -- still not 100% elegant
60 # though
61 # 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
62 # return values (the system uname command tends to return
63 # 'unknown' instead of just leaving the field emtpy)
64 # 0.5.1 - included code for slackware dist; added exception handlers
65 # to cover up situations where platforms don't have os.popen
66 # (e.g. Mac) or fail on socket.gethostname(); fixed libc
67 # detection RE
68 # 0.5.0 - changed the API names referring to system commands to *syscmd*;
69 # added java_ver(); made syscmd_ver() a private
70 # API (was system_ver() in previous versions) -- use uname()
71 # instead; extended the win32_ver() to also return processor
72 # type information
73 # 0.4.0 - added win32_ver() and modified the platform() output for WinXX
74 # 0.3.4 - fixed a bug in _follow_symlinks()
75 # 0.3.3 - fixed popen() and "file" command invokation bugs
76 # 0.3.2 - added architecture() API and support for it in platform()
77 # 0.3.1 - fixed syscmd_ver() RE to support Windows NT
78 # 0.3.0 - added system alias support
79 # 0.2.3 - removed 'wince' again... oh well.
80 # 0.2.2 - added 'wince' to syscmd_ver() supported platforms
81 # 0.2.1 - added cache logic and changed the platform string format
82 # 0.2.0 - changed the API to use functions instead of module globals
83 # since some action take too long to be run on module import
84 # 0.1.0 - first release
86 # You can always get the latest version of this module at:
88 # http://www.egenix.com/files/python/platform.py
90 # If that URL should fail, try contacting the author.
92 __copyright__ = """
93 Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
94 Copyright (c) 2000-2007, eGenix.com Software GmbH; mailto:info@egenix.com
96 Permission to use, copy, modify, and distribute this software and its
97 documentation for any purpose and without fee or royalty is hereby granted,
98 provided that the above copyright notice appear in all copies and that
99 both that copyright notice and this permission notice appear in
100 supporting documentation or portions thereof, including modifications,
101 that you make.
103 EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
104 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
105 FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
106 INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
107 FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
108 NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
109 WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
113 __version__ = '1.0.6'
115 import sys,string,os,re
117 ### Platform specific APIs
119 _libc_search = re.compile(r'(__libc_init)'
121 '(GLIBC_([0-9.]+))'
123 '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
125 def libc_ver(executable=sys.executable,lib='',version='',
127 chunksize=2048):
129 """ Tries to determine the libc version that the file executable
130 (which defaults to the Python interpreter) is linked against.
132 Returns a tuple of strings (lib,version) which default to the
133 given parameters in case the lookup fails.
135 Note that the function has intimate knowledge of how different
136 libc versions add symbols to the executable and thus is probably
137 only useable for executables compiled using gcc.
139 The file is read and scanned in chunks of chunksize bytes.
142 if hasattr(os.path, 'realpath'):
143 # Python 2.2 introduced os.path.realpath(); it is used
144 # here to work around problems with Cygwin not being
145 # able to open symlinks for reading
146 executable = os.path.realpath(executable)
147 f = open(executable,'rb')
148 binary = f.read(chunksize)
149 pos = 0
150 while 1:
151 m = _libc_search.search(binary,pos)
152 if not m:
153 binary = f.read(chunksize)
154 if not binary:
155 break
156 pos = 0
157 continue
158 libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
159 if libcinit and not lib:
160 lib = 'libc'
161 elif glibc:
162 if lib != 'glibc':
163 lib = 'glibc'
164 version = glibcversion
165 elif glibcversion > version:
166 version = glibcversion
167 elif so:
168 if lib != 'glibc':
169 lib = 'libc'
170 if soversion > version:
171 version = soversion
172 if threads and version[-len(threads):] != threads:
173 version = version + threads
174 pos = m.end()
175 f.close()
176 return lib,version
178 def _dist_try_harder(distname,version,id):
180 """ Tries some special tricks to get the distribution
181 information in case the default method fails.
183 Currently supports older SuSE Linux, Caldera OpenLinux and
184 Slackware Linux distributions.
187 if os.path.exists('/var/adm/inst-log/info'):
188 # SuSE Linux stores distribution information in that file
189 info = open('/var/adm/inst-log/info').readlines()
190 distname = 'SuSE'
191 for line in info:
192 tv = string.split(line)
193 if len(tv) == 2:
194 tag,value = tv
195 else:
196 continue
197 if tag == 'MIN_DIST_VERSION':
198 version = string.strip(value)
199 elif tag == 'DIST_IDENT':
200 values = string.split(value,'-')
201 id = values[2]
202 return distname,version,id
204 if os.path.exists('/etc/.installed'):
205 # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
206 info = open('/etc/.installed').readlines()
207 for line in info:
208 pkg = string.split(line,'-')
209 if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
210 # XXX does Caldera support non Intel platforms ? If yes,
211 # where can we find the needed id ?
212 return 'OpenLinux',pkg[1],id
214 if os.path.isdir('/usr/lib/setup'):
215 # Check for slackware verson tag file (thanks to Greg Andruk)
216 verfiles = os.listdir('/usr/lib/setup')
217 for n in range(len(verfiles)-1, -1, -1):
218 if verfiles[n][:14] != 'slack-version-':
219 del verfiles[n]
220 if verfiles:
221 verfiles.sort()
222 distname = 'slackware'
223 version = verfiles[-1][14:]
224 return distname,version,id
226 return distname,version,id
228 _release_filename = re.compile(r'(\w+)[-_](release|version)')
229 _lsb_release_version = re.compile(r'(.+)'
230 ' release '
231 '([\d.]+)'
232 '[^(]*(?:\((.+)\))?')
233 _release_version = re.compile(r'([^0-9]+)'
234 '(?: release )?'
235 '([\d.]+)'
236 '[^(]*(?:\((.+)\))?')
238 # See also http://www.novell.com/coolsolutions/feature/11251.html
239 # and http://linuxmafia.com/faq/Admin/release-files.html
240 # and http://data.linux-ntfs.org/rpm/whichrpm
241 # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
243 _supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos',
244 'mandrake', 'rocks', 'slackware', 'yellowdog',
245 'gentoo', 'UnitedLinux')
247 def _parse_release_file(firstline):
249 # Parse the first line
250 m = _lsb_release_version.match(firstline)
251 if m is not None:
252 # LSB format: "distro release x.x (codename)"
253 return tuple(m.groups())
255 # Pre-LSB format: "distro x.x (codename)"
256 m = _release_version.match(firstline)
257 if m is not None:
258 return tuple(m.groups())
260 # Unkown format... take the first two words
261 l = string.split(string.strip(firstline))
262 if l:
263 version = l[0]
264 if len(l) > 1:
265 id = l[1]
266 else:
267 id = ''
268 return '', version, id
270 def _test_parse_release_file():
272 for input, output in (
273 # Examples of release file contents:
274 ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))
275 ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))
276 ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))
277 ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))
278 ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))
279 ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))
280 ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))
281 ('CentOS release 4', ('CentOS', '4', None))
282 ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia'))
284 parsed = _parse_release_file(input)
285 if parsed != output:
286 print (input, parsed)
288 def linux_distribution(distname='', version='', id='',
290 supported_dists=_supported_dists,
291 full_distribution_name=1):
293 """ Tries to determine the name of the Linux OS distribution name.
295 The function first looks for a distribution release file in
296 /etc and then reverts to _dist_try_harder() in case no
297 suitable files are found.
299 supported_dists may be given to define the set of Linux
300 distributions to look for. It defaults to a list of currently
301 supported Linux distributions identified by their release file
302 name.
304 If full_distribution_name is true (default), the full
305 distribution read from the OS is returned. Otherwise the short
306 name taken from supported_dists is used.
308 Returns a tuple (distname,version,id) which default to the
309 args given as parameters.
312 try:
313 etc = os.listdir('/etc')
314 except os.error:
315 # Probably not a Unix system
316 return distname,version,id
317 etc.sort()
318 for file in etc:
319 m = _release_filename.match(file)
320 if m is not None:
321 _distname,dummy = m.groups()
322 if _distname in supported_dists:
323 distname = _distname
324 break
325 else:
326 return _dist_try_harder(distname,version,id)
328 # Read the first line
329 f = open('/etc/'+file, 'r')
330 firstline = f.readline()
331 f.close()
332 _distname, _version, _id = _parse_release_file(firstline)
334 if _distname and full_distribution_name:
335 distname = _distname
336 if _version:
337 version = _version
338 if _id:
339 id = _id
340 return distname, version, id
342 # To maintain backwards compatibility:
344 def dist(distname='',version='',id='',
346 supported_dists=_supported_dists):
348 """ Tries to determine the name of the Linux OS distribution name.
350 The function first looks for a distribution release file in
351 /etc and then reverts to _dist_try_harder() in case no
352 suitable files are found.
354 Returns a tuple (distname,version,id) which default to the
355 args given as parameters.
358 return linux_distribution(distname, version, id,
359 supported_dists=supported_dists,
360 full_distribution_name=0)
362 class _popen:
364 """ Fairly portable (alternative) popen implementation.
366 This is mostly needed in case os.popen() is not available, or
367 doesn't work as advertised, e.g. in Win9X GUI programs like
368 PythonWin or IDLE.
370 Writing to the pipe is currently not supported.
373 tmpfile = ''
374 pipe = None
375 bufsize = None
376 mode = 'r'
378 def __init__(self,cmd,mode='r',bufsize=None):
380 if mode != 'r':
381 raise ValueError,'popen()-emulation only supports read mode'
382 import tempfile
383 self.tmpfile = tmpfile = tempfile.mktemp()
384 os.system(cmd + ' > %s' % tmpfile)
385 self.pipe = open(tmpfile,'rb')
386 self.bufsize = bufsize
387 self.mode = mode
389 def read(self):
391 return self.pipe.read()
393 def readlines(self):
395 if self.bufsize is not None:
396 return self.pipe.readlines()
398 def close(self,
400 remove=os.unlink,error=os.error):
402 if self.pipe:
403 rc = self.pipe.close()
404 else:
405 rc = 255
406 if self.tmpfile:
407 try:
408 remove(self.tmpfile)
409 except error:
410 pass
411 return rc
413 # Alias
414 __del__ = close
416 def popen(cmd, mode='r', bufsize=None):
418 """ Portable popen() interface.
420 # Find a working popen implementation preferring win32pipe.popen
421 # over os.popen over _popen
422 popen = None
423 if os.environ.get('OS','') == 'Windows_NT':
424 # On NT win32pipe should work; on Win9x it hangs due to bugs
425 # in the MS C lib (see MS KnowledgeBase article Q150956)
426 try:
427 import win32pipe
428 except ImportError:
429 pass
430 else:
431 popen = win32pipe.popen
432 if popen is None:
433 if hasattr(os,'popen'):
434 popen = os.popen
435 # Check whether it works... it doesn't in GUI programs
436 # on Windows platforms
437 if sys.platform == 'win32': # XXX Others too ?
438 try:
439 popen('')
440 except os.error:
441 popen = _popen
442 else:
443 popen = _popen
444 if bufsize is None:
445 return popen(cmd,mode)
446 else:
447 return popen(cmd,mode,bufsize)
449 def _norm_version(version, build=''):
451 """ Normalize the version and build strings and return a single
452 version string using the format major.minor.build (or patchlevel).
454 l = string.split(version,'.')
455 if build:
456 l.append(build)
457 try:
458 ints = map(int,l)
459 except ValueError:
460 strings = l
461 else:
462 strings = map(str,ints)
463 version = string.join(strings[:3],'.')
464 return version
466 _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
467 '.*'
468 'Version ([\d.]+))')
470 def _syscmd_ver(system='', release='', version='',
472 supported_platforms=('win32','win16','dos','os2')):
474 """ Tries to figure out the OS version used and returns
475 a tuple (system,release,version).
477 It uses the "ver" shell command for this which is known
478 to exists on Windows, DOS and OS/2. XXX Others too ?
480 In case this fails, the given parameters are used as
481 defaults.
484 if sys.platform not in supported_platforms:
485 return system,release,version
487 # Try some common cmd strings
488 for cmd in ('ver','command /c ver','cmd /c ver'):
489 try:
490 pipe = popen(cmd)
491 info = pipe.read()
492 if pipe.close():
493 raise os.error,'command failed'
494 # XXX How can I supress shell errors from being written
495 # to stderr ?
496 except os.error,why:
497 #print 'Command %s failed: %s' % (cmd,why)
498 continue
499 except IOError,why:
500 #print 'Command %s failed: %s' % (cmd,why)
501 continue
502 else:
503 break
504 else:
505 return system,release,version
507 # Parse the output
508 info = string.strip(info)
509 m = _ver_output.match(info)
510 if m is not None:
511 system,release,version = m.groups()
512 # Strip trailing dots from version and release
513 if release[-1] == '.':
514 release = release[:-1]
515 if version[-1] == '.':
516 version = version[:-1]
517 # Normalize the version and build strings (eliminating additional
518 # zeros)
519 version = _norm_version(version)
520 return system,release,version
522 def _win32_getvalue(key,name,default=''):
524 """ Read a value for name from the registry key.
526 In case this fails, default is returned.
529 from win32api import RegQueryValueEx
530 try:
531 return RegQueryValueEx(key,name)
532 except:
533 return default
535 def win32_ver(release='',version='',csd='',ptype=''):
537 """ Get additional version information from the Windows Registry
538 and return a tuple (version,csd,ptype) referring to version
539 number, CSD level and OS type (multi/single
540 processor).
542 As a hint: ptype returns 'Uniprocessor Free' on single
543 processor NT machines and 'Multiprocessor Free' on multi
544 processor machines. The 'Free' refers to the OS version being
545 free of debugging code. It could also state 'Checked' which
546 means the OS version uses debugging code, i.e. code that
547 checks arguments, ranges, etc. (Thomas Heller).
549 Note: this function only works if Mark Hammond's win32
550 package is installed and obviously only runs on Win32
551 compatible platforms.
554 # XXX Is there any way to find out the processor type on WinXX ?
555 # XXX Is win32 available on Windows CE ?
557 # Adapted from code posted by Karl Putland to comp.lang.python.
559 # The mappings between reg. values and release names can be found
560 # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
562 # Import the needed APIs
563 try:
564 import win32api
565 except ImportError:
566 return release,version,csd,ptype
567 from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx
568 from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\
569 VER_PLATFORM_WIN32_WINDOWS
571 # Find out the registry key and some general version infos
572 maj,min,buildno,plat,csd = GetVersionEx()
573 version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
574 if csd[:13] == 'Service Pack ':
575 csd = 'SP' + csd[13:]
576 if plat == VER_PLATFORM_WIN32_WINDOWS:
577 regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
578 # Try to guess the release name
579 if maj == 4:
580 if min == 0:
581 release = '95'
582 elif min == 10:
583 release = '98'
584 elif min == 90:
585 release = 'Me'
586 else:
587 release = 'postMe'
588 elif maj == 5:
589 release = '2000'
590 elif plat == VER_PLATFORM_WIN32_NT:
591 regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
592 if maj <= 4:
593 release = 'NT'
594 elif maj == 5:
595 if min == 0:
596 release = '2000'
597 elif min == 1:
598 release = 'XP'
599 elif min == 2:
600 release = '2003Server'
601 else:
602 release = 'post2003'
603 else:
604 if not release:
605 # E.g. Win3.1 with win32s
606 release = '%i.%i' % (maj,min)
607 return release,version,csd,ptype
609 # Open the registry key
610 try:
611 keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey)
612 # Get a value to make sure the key exists...
613 RegQueryValueEx(keyCurVer,'SystemRoot')
614 except:
615 return release,version,csd,ptype
617 # Parse values
618 #subversion = _win32_getvalue(keyCurVer,
619 # 'SubVersionNumber',
620 # ('',1))[0]
621 #if subversion:
622 # release = release + subversion # 95a, 95b, etc.
623 build = _win32_getvalue(keyCurVer,
624 'CurrentBuildNumber',
625 ('',1))[0]
626 ptype = _win32_getvalue(keyCurVer,
627 'CurrentType',
628 (ptype,1))[0]
630 # Normalize version
631 version = _norm_version(version,build)
633 # Close key
634 RegCloseKey(keyCurVer)
635 return release,version,csd,ptype
637 def _mac_ver_lookup(selectors,default=None):
639 from gestalt import gestalt
640 import MacOS
641 l = []
642 append = l.append
643 for selector in selectors:
644 try:
645 append(gestalt(selector))
646 except (RuntimeError, MacOS.Error):
647 append(default)
648 return l
650 def _bcd2str(bcd):
652 return hex(bcd)[2:]
654 def mac_ver(release='',versioninfo=('','',''),machine=''):
656 """ Get MacOS version information and return it as tuple (release,
657 versioninfo, machine) with versioninfo being a tuple (version,
658 dev_stage, non_release_version).
660 Entries which cannot be determined are set to the paramter values
661 which default to ''. All tuple entries are strings.
663 Thanks to Mark R. Levinson for mailing documentation links and
664 code examples for this function. Documentation for the
665 gestalt() API is available online at:
667 http://www.rgaros.nl/gestalt/
670 # Check whether the version info module is available
671 try:
672 import gestalt
673 import MacOS
674 except ImportError:
675 return release,versioninfo,machine
676 # Get the infos
677 sysv,sysu,sysa = _mac_ver_lookup(('sysv','sysu','sysa'))
678 # Decode the infos
679 if sysv:
680 major = (sysv & 0xFF00) >> 8
681 minor = (sysv & 0x00F0) >> 4
682 patch = (sysv & 0x000F)
683 release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
684 if sysu:
685 major = int((sysu & 0xFF000000L) >> 24)
686 minor = (sysu & 0x00F00000) >> 20
687 bugfix = (sysu & 0x000F0000) >> 16
688 stage = (sysu & 0x0000FF00) >> 8
689 nonrel = (sysu & 0x000000FF)
690 version = '%s.%i.%i' % (_bcd2str(major),minor,bugfix)
691 nonrel = _bcd2str(nonrel)
692 stage = {0x20:'development',
693 0x40:'alpha',
694 0x60:'beta',
695 0x80:'final'}.get(stage,'')
696 versioninfo = (version,stage,nonrel)
697 if sysa:
698 machine = {0x1: '68k',
699 0x2: 'PowerPC',
700 0xa: 'i386'}.get(sysa,'')
701 return release,versioninfo,machine
703 def _java_getprop(name,default):
705 from java.lang import System
706 try:
707 value = System.getProperty(name)
708 if value is None:
709 return default
710 return value
711 except AttributeError:
712 return default
714 def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
716 """ Version interface for Jython.
718 Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
719 a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
720 tuple (os_name,os_version,os_arch).
722 Values which cannot be determined are set to the defaults
723 given as parameters (which all default to '').
726 # Import the needed APIs
727 try:
728 import java.lang
729 except ImportError:
730 return release,vendor,vminfo,osinfo
732 vendor = _java_getprop('java.vendor', vendor)
733 release = _java_getprop('java.version', release)
734 vm_name, vm_release, vm_vendor = vminfo
735 vm_name = _java_getprop('java.vm.name', vm_name)
736 vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
737 vm_release = _java_getprop('java.vm.version', vm_release)
738 vminfo = vm_name, vm_release, vm_vendor
739 os_name, os_version, os_arch = osinfo
740 os_arch = _java_getprop('java.os.arch', os_arch)
741 os_name = _java_getprop('java.os.name', os_name)
742 os_version = _java_getprop('java.os.version', os_version)
743 osinfo = os_name, os_version, os_arch
745 return release, vendor, vminfo, osinfo
747 ### System name aliasing
749 def system_alias(system,release,version):
751 """ Returns (system,release,version) aliased to common
752 marketing names used for some systems.
754 It also does some reordering of the information in some cases
755 where it would otherwise cause confusion.
758 if system == 'Rhapsody':
759 # Apple's BSD derivative
760 # XXX How can we determine the marketing release number ?
761 return 'MacOS X Server',system+release,version
763 elif system == 'SunOS':
764 # Sun's OS
765 if release < '5':
766 # These releases use the old name SunOS
767 return system,release,version
768 # Modify release (marketing release = SunOS release - 3)
769 l = string.split(release,'.')
770 if l:
771 try:
772 major = int(l[0])
773 except ValueError:
774 pass
775 else:
776 major = major - 3
777 l[0] = str(major)
778 release = string.join(l,'.')
779 if release < '6':
780 system = 'Solaris'
781 else:
782 # XXX Whatever the new SunOS marketing name is...
783 system = 'Solaris'
785 elif system == 'IRIX64':
786 # IRIX reports IRIX64 on platforms with 64-bit support; yet it
787 # is really a version and not a different platform, since 32-bit
788 # apps are also supported..
789 system = 'IRIX'
790 if version:
791 version = version + ' (64bit)'
792 else:
793 version = '64bit'
795 elif system in ('win32','win16'):
796 # In case one of the other tricks
797 system = 'Windows'
799 return system,release,version
801 ### Various internal helpers
803 def _platform(*args):
805 """ Helper to format the platform string in a filename
806 compatible format e.g. "system-version-machine".
808 # Format the platform string
809 platform = string.join(
810 map(string.strip,
811 filter(len, args)),
812 '-')
814 # Cleanup some possible filename obstacles...
815 replace = string.replace
816 platform = replace(platform,' ','_')
817 platform = replace(platform,'/','-')
818 platform = replace(platform,'\\','-')
819 platform = replace(platform,':','-')
820 platform = replace(platform,';','-')
821 platform = replace(platform,'"','-')
822 platform = replace(platform,'(','-')
823 platform = replace(platform,')','-')
825 # No need to report 'unknown' information...
826 platform = replace(platform,'unknown','')
828 # Fold '--'s and remove trailing '-'
829 while 1:
830 cleaned = replace(platform,'--','-')
831 if cleaned == platform:
832 break
833 platform = cleaned
834 while platform[-1] == '-':
835 platform = platform[:-1]
837 return platform
839 def _node(default=''):
841 """ Helper to determine the node name of this machine.
843 try:
844 import socket
845 except ImportError:
846 # No sockets...
847 return default
848 try:
849 return socket.gethostname()
850 except socket.error:
851 # Still not working...
852 return default
854 # os.path.abspath is new in Python 1.5.2:
855 if not hasattr(os.path,'abspath'):
857 def _abspath(path,
859 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
860 normpath=os.path.normpath):
862 if not isabs(path):
863 path = join(getcwd(), path)
864 return normpath(path)
866 else:
868 _abspath = os.path.abspath
870 def _follow_symlinks(filepath):
872 """ In case filepath is a symlink, follow it until a
873 real file is reached.
875 filepath = _abspath(filepath)
876 while os.path.islink(filepath):
877 filepath = os.path.normpath(
878 os.path.join(filepath,os.readlink(filepath)))
879 return filepath
881 def _syscmd_uname(option,default=''):
883 """ Interface to the system's uname command.
885 if sys.platform in ('dos','win32','win16','os2'):
886 # XXX Others too ?
887 return default
888 try:
889 f = os.popen('uname %s 2> /dev/null' % option)
890 except (AttributeError,os.error):
891 return default
892 output = string.strip(f.read())
893 rc = f.close()
894 if not output or rc:
895 return default
896 else:
897 return output
899 def _syscmd_file(target,default=''):
901 """ Interface to the system's file command.
903 The function uses the -b option of the file command to have it
904 ommit the filename in its output and if possible the -L option
905 to have the command follow symlinks. It returns default in
906 case the command should fail.
909 target = _follow_symlinks(target)
910 try:
911 f = os.popen('file %s 2> /dev/null' % target)
912 except (AttributeError,os.error):
913 return default
914 output = string.strip(f.read())
915 rc = f.close()
916 if not output or rc:
917 return default
918 else:
919 return output
921 ### Information about the used architecture
923 # Default values for architecture; non-empty strings override the
924 # defaults given as parameters
925 _default_architecture = {
926 'win32': ('','WindowsPE'),
927 'win16': ('','Windows'),
928 'dos': ('','MSDOS'),
931 _architecture_split = re.compile(r'[\s,]').split
933 def architecture(executable=sys.executable,bits='',linkage=''):
935 """ Queries the given executable (defaults to the Python interpreter
936 binary) for various architecture information.
938 Returns a tuple (bits,linkage) which contains information about
939 the bit architecture and the linkage format used for the
940 executable. Both values are returned as strings.
942 Values that cannot be determined are returned as given by the
943 parameter presets. If bits is given as '', the sizeof(pointer)
944 (or sizeof(long) on Python version < 1.5.2) is used as
945 indicator for the supported pointer size.
947 The function relies on the system's "file" command to do the
948 actual work. This is available on most if not all Unix
949 platforms. On some non-Unix platforms where the "file" command
950 does not exist and the executable is set to the Python interpreter
951 binary defaults from _default_architecture are used.
954 # Use the sizeof(pointer) as default number of bits if nothing
955 # else is given as default.
956 if not bits:
957 import struct
958 try:
959 size = struct.calcsize('P')
960 except struct.error:
961 # Older installations can only query longs
962 size = struct.calcsize('l')
963 bits = str(size*8) + 'bit'
965 # Get data from the 'file' system command
966 if executable:
967 output = _syscmd_file(executable, '')
968 else:
969 output = ''
971 if not output and \
972 executable == sys.executable:
973 # "file" command did not return anything; we'll try to provide
974 # some sensible defaults then...
975 if _default_architecture.has_key(sys.platform):
976 b,l = _default_architecture[sys.platform]
977 if b:
978 bits = b
979 if l:
980 linkage = l
981 return bits,linkage
983 # Split the output into a list of strings omitting the filename
984 fileout = _architecture_split(output)[1:]
986 if 'executable' not in fileout:
987 # Format not supported
988 return bits,linkage
990 # Bits
991 if '32-bit' in fileout:
992 bits = '32bit'
993 elif 'N32' in fileout:
994 # On Irix only
995 bits = 'n32bit'
996 elif '64-bit' in fileout:
997 bits = '64bit'
999 # Linkage
1000 if 'ELF' in fileout:
1001 linkage = 'ELF'
1002 elif 'PE' in fileout:
1003 # E.g. Windows uses this format
1004 if 'Windows' in fileout:
1005 linkage = 'WindowsPE'
1006 else:
1007 linkage = 'PE'
1008 elif 'COFF' in fileout:
1009 linkage = 'COFF'
1010 elif 'MS-DOS' in fileout:
1011 linkage = 'MSDOS'
1012 else:
1013 # XXX the A.OUT format also falls under this class...
1014 pass
1016 return bits,linkage
1018 ### Portable uname() interface
1020 _uname_cache = None
1022 def uname():
1024 """ Fairly portable uname interface. Returns a tuple
1025 of strings (system,node,release,version,machine,processor)
1026 identifying the underlying platform.
1028 Note that unlike the os.uname function this also returns
1029 possible processor information as an additional tuple entry.
1031 Entries which cannot be determined are set to ''.
1034 global _uname_cache
1036 if _uname_cache is not None:
1037 return _uname_cache
1039 # Get some infos from the builtin os.uname API...
1040 try:
1041 system,node,release,version,machine = os.uname()
1043 except AttributeError:
1044 # Hmm, no uname... we'll have to poke around the system then.
1045 system = sys.platform
1046 release = ''
1047 version = ''
1048 node = _node()
1049 machine = ''
1050 processor = ''
1051 use_syscmd_ver = 1
1053 # Try win32_ver() on win32 platforms
1054 if system == 'win32':
1055 release,version,csd,ptype = win32_ver()
1056 if release and version:
1057 use_syscmd_ver = 0
1058 # XXX Should try to parse the PROCESSOR_* environment variables
1059 # available on Win XP and later; see
1060 # http://support.microsoft.com/kb/888731 and
1061 # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
1063 # Try the 'ver' system command available on some
1064 # platforms
1065 if use_syscmd_ver:
1066 system,release,version = _syscmd_ver(system)
1067 # Normalize system to what win32_ver() normally returns
1068 # (_syscmd_ver() tends to return the vendor name as well)
1069 if system == 'Microsoft Windows':
1070 system = 'Windows'
1072 # In case we still don't know anything useful, we'll try to
1073 # help ourselves
1074 if system in ('win32','win16'):
1075 if not version:
1076 if system == 'win32':
1077 version = '32bit'
1078 else:
1079 version = '16bit'
1080 system = 'Windows'
1082 elif system[:4] == 'java':
1083 release,vendor,vminfo,osinfo = java_ver()
1084 system = 'Java'
1085 version = string.join(vminfo,', ')
1086 if not version:
1087 version = vendor
1089 elif os.name == 'mac':
1090 release,(version,stage,nonrel),machine = mac_ver()
1091 system = 'MacOS'
1093 else:
1094 # System specific extensions
1095 if system == 'OpenVMS':
1096 # OpenVMS seems to have release and version mixed up
1097 if not release or release == '0':
1098 release = version
1099 version = ''
1100 # Get processor information
1101 try:
1102 import vms_lib
1103 except ImportError:
1104 pass
1105 else:
1106 csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
1107 if (cpu_number >= 128):
1108 processor = 'Alpha'
1109 else:
1110 processor = 'VAX'
1111 else:
1112 # Get processor information from the uname system command
1113 processor = _syscmd_uname('-p','')
1115 # 'unknown' is not really any useful as information; we'll convert
1116 # it to '' which is more portable
1117 if system == 'unknown':
1118 system = ''
1119 if node == 'unknown':
1120 node = ''
1121 if release == 'unknown':
1122 release = ''
1123 if version == 'unknown':
1124 version = ''
1125 if machine == 'unknown':
1126 machine = ''
1127 if processor == 'unknown':
1128 processor = ''
1129 _uname_cache = system,node,release,version,machine,processor
1130 return _uname_cache
1132 ### Direct interfaces to some of the uname() return values
1134 def system():
1136 """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
1138 An empty string is returned if the value cannot be determined.
1141 return uname()[0]
1143 def node():
1145 """ Returns the computer's network name (which may not be fully
1146 qualified)
1148 An empty string is returned if the value cannot be determined.
1151 return uname()[1]
1153 def release():
1155 """ Returns the system's release, e.g. '2.2.0' or 'NT'
1157 An empty string is returned if the value cannot be determined.
1160 return uname()[2]
1162 def version():
1164 """ Returns the system's release version, e.g. '#3 on degas'
1166 An empty string is returned if the value cannot be determined.
1169 return uname()[3]
1171 def machine():
1173 """ Returns the machine type, e.g. 'i386'
1175 An empty string is returned if the value cannot be determined.
1178 return uname()[4]
1180 def processor():
1182 """ Returns the (true) processor name, e.g. 'amdk6'
1184 An empty string is returned if the value cannot be
1185 determined. Note that many platforms do not provide this
1186 information or simply return the same value as for machine(),
1187 e.g. NetBSD does this.
1190 return uname()[5]
1192 ### Various APIs for extracting information from sys.version
1194 _sys_version_parser = re.compile(
1195 r'([\w.+]+)\s*'
1196 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
1197 '\[([^\]]+)\]?')
1199 _jython_sys_version_parser = re.compile(
1200 r'([\d\.]+)')
1202 _ironpython_sys_version_parser = re.compile(
1203 r'IronPython\s*'
1204 '([\d\.]+)'
1205 '(?: \(([\d\.]+)\))?'
1206 ' on (.NET [\d\.]+)')
1208 _sys_version_cache = {}
1210 def _sys_version(sys_version=None):
1212 """ Returns a parsed version of Python's sys.version as tuple
1213 (name, version, branch, revision, buildno, builddate, compiler)
1214 referring to the Python implementation name, version, branch,
1215 revision, build number, build date/time as string and the compiler
1216 identification string.
1218 Note that unlike the Python sys.version, the returned value
1219 for the Python version will always include the patchlevel (it
1220 defaults to '.0').
1222 The function returns empty strings for tuple entries that
1223 cannot be determined.
1225 sys_version may be given to parse an alternative version
1226 string, e.g. if the version was read from a different Python
1227 interpreter.
1230 # Get the Python version
1231 if sys_version is None:
1232 sys_version = sys.version
1234 # Try the cache first
1235 result = _sys_version_cache.get(sys_version, None)
1236 if result is not None:
1237 return result
1239 # Parse it
1240 if sys_version[:10] == 'IronPython':
1241 # IronPython
1242 name = 'IronPython'
1243 match = _ironpython_sys_version_parser.match(sys_version)
1244 if match is None:
1245 raise ValueError(
1246 'failed to parse IronPython sys.version: %s' %
1247 repr(sys_version))
1248 version, alt_version, compiler = match.groups()
1249 branch = ''
1250 revision = ''
1251 buildno = ''
1252 builddate = ''
1254 elif sys.platform[:4] == 'java':
1255 # Jython
1256 name = 'Jython'
1257 match = _jython_sys_version_parser.match(sys_version)
1258 if match is None:
1259 raise ValueError(
1260 'failed to parse Jython sys.version: %s' %
1261 repr(sys_version))
1262 version, = match.groups()
1263 branch = ''
1264 revision = ''
1265 compiler = sys.platform
1266 buildno = ''
1267 builddate = ''
1269 else:
1270 # CPython
1271 match = _sys_version_parser.match(sys_version)
1272 if match is None:
1273 raise ValueError(
1274 'failed to parse CPython sys.version: %s' %
1275 repr(sys_version))
1276 version, buildno, builddate, buildtime, compiler = \
1277 match.groups()
1278 if hasattr(sys, 'subversion'):
1279 # sys.subversion was added in Python 2.5
1280 name, branch, revision = sys.subversion
1281 else:
1282 name = 'CPython'
1283 branch = ''
1284 revision = ''
1285 builddate = builddate + ' ' + buildtime
1287 # Add the patchlevel version if missing
1288 l = string.split(version, '.')
1289 if len(l) == 2:
1290 l.append('0')
1291 version = string.join(l, '.')
1293 # Build and cache the result
1294 result = (name, version, branch, revision, buildno, builddate, compiler)
1295 _sys_version_cache[sys_version] = result
1296 return result
1298 def _test_sys_version():
1300 _sys_version_cache.clear()
1301 for input, output in (
1302 ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
1303 ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
1304 ('IronPython 1.0.60816 on .NET 2.0.50727.42',
1305 ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
1306 ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
1307 ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
1309 parsed = _sys_version(input)
1310 if parsed != output:
1311 print (input, parsed)
1313 def python_implementation():
1315 """ Returns a string identifying the Python implementation.
1317 Currently, the following implementations are identified:
1318 'CPython' (C implementation of Python),
1319 'IronPython' (.NET implementation of Python),
1320 'Jython' (Java implementation of Python).
1323 return _sys_version()[0]
1325 def python_version():
1327 """ Returns the Python version as string 'major.minor.patchlevel'
1329 Note that unlike the Python sys.version, the returned value
1330 will always include the patchlevel (it defaults to 0).
1333 if hasattr(sys, 'version_info'):
1334 return '%i.%i.%i' % sys.version_info[:3]
1335 return _sys_version()[1]
1337 def python_version_tuple():
1339 """ Returns the Python version as tuple (major, minor, patchlevel)
1340 of strings.
1342 Note that unlike the Python sys.version, the returned value
1343 will always include the patchlevel (it defaults to 0).
1346 if hasattr(sys, 'version_info'):
1347 return sys.version_info[:3]
1348 return tuple(string.split(_sys_version()[1], '.'))
1350 def python_branch():
1352 """ Returns a string identifying the Python implementation
1353 branch.
1355 For CPython this is the Subversion branch from which the
1356 Python binary was built.
1358 If not available, an empty string is returned.
1362 return _sys_version()[2]
1364 def python_revision():
1366 """ Returns a string identifying the Python implementation
1367 revision.
1369 For CPython this is the Subversion revision from which the
1370 Python binary was built.
1372 If not available, an empty string is returned.
1375 return _sys_version()[3]
1377 def python_build():
1379 """ Returns a tuple (buildno, builddate) stating the Python
1380 build number and date as strings.
1383 return _sys_version()[4:6]
1385 def python_compiler():
1387 """ Returns a string identifying the compiler used for compiling
1388 Python.
1391 return _sys_version()[6]
1393 ### The Opus Magnum of platform strings :-)
1395 _platform_cache = {}
1397 def platform(aliased=0, terse=0):
1399 """ Returns a single string identifying the underlying platform
1400 with as much useful information as possible (but no more :).
1402 The output is intended to be human readable rather than
1403 machine parseable. It may look different on different
1404 platforms and this is intended.
1406 If "aliased" is true, the function will use aliases for
1407 various platforms that report system names which differ from
1408 their common names, e.g. SunOS will be reported as
1409 Solaris. The system_alias() function is used to implement
1410 this.
1412 Setting terse to true causes the function to return only the
1413 absolute minimum information needed to identify the platform.
1416 result = _platform_cache.get((aliased, terse), None)
1417 if result is not None:
1418 return result
1420 # Get uname information and then apply platform specific cosmetics
1421 # to it...
1422 system,node,release,version,machine,processor = uname()
1423 if machine == processor:
1424 processor = ''
1425 if aliased:
1426 system,release,version = system_alias(system,release,version)
1428 if system == 'Windows':
1429 # MS platforms
1430 rel,vers,csd,ptype = win32_ver(version)
1431 if terse:
1432 platform = _platform(system,release)
1433 else:
1434 platform = _platform(system,release,version,csd)
1436 elif system in ('Linux',):
1437 # Linux based systems
1438 distname,distversion,distid = dist('')
1439 if distname and not terse:
1440 platform = _platform(system,release,machine,processor,
1441 'with',
1442 distname,distversion,distid)
1443 else:
1444 # If the distribution name is unknown check for libc vs. glibc
1445 libcname,libcversion = libc_ver(sys.executable)
1446 platform = _platform(system,release,machine,processor,
1447 'with',
1448 libcname+libcversion)
1449 elif system == 'Java':
1450 # Java platforms
1451 r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
1452 if terse or not os_name:
1453 platform = _platform(system,release,version)
1454 else:
1455 platform = _platform(system,release,version,
1456 'on',
1457 os_name,os_version,os_arch)
1459 elif system == 'MacOS':
1460 # MacOS platforms
1461 if terse:
1462 platform = _platform(system,release)
1463 else:
1464 platform = _platform(system,release,machine)
1466 else:
1467 # Generic handler
1468 if terse:
1469 platform = _platform(system,release)
1470 else:
1471 bits,linkage = architecture(sys.executable)
1472 platform = _platform(system,release,machine,processor,bits,linkage)
1474 _platform_cache[(aliased, terse)] = platform
1475 return platform
1477 ### Command line interface
1479 if __name__ == '__main__':
1480 # Default is to print the aliased verbose platform string
1481 terse = ('terse' in sys.argv or '--terse' in sys.argv)
1482 aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
1483 print platform(aliased,terse)
1484 sys.exit(0)