Debian Codegraph @

cpython27/Lib/platform.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 """ This module tries to retrieve as much platform-identifying data as
4 possible. It makes this information available via function APIs.
5
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.
9
10 """
11 # This module is maintained by Marc-Andre Lemburg <[email protected]>.
12 # If you find problems, please submit bug reports/patches via the
13 # Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
14 #
15 # Note: Please keep this module compatible to Python 1.5.2.
16 #
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
22 #
23 # Many thanks to all those who helped adding platform-specific
24 # checks (in no particular order):
25 #
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, Steve
32 # Dower
33 #
34 # History:
35 #
36 # <see CVS and SVN checkin messages for history>
37 #
38 # 1.0.8 - changed Windows support to read version from kernel32.dll
39 # 1.0.7 - added DEV_NULL
40 # 1.0.6 - added linux_distribution()
41 # 1.0.5 - fixed Java support to allow running the module on Jython
42 # 1.0.4 - added IronPython support
43 # 1.0.3 - added normalization of Windows system name
44 # 1.0.2 - added more Windows support
45 # 1.0.1 - reformatted to make doc.py happy
46 # 1.0.0 - reformatted a bit and checked into Python CVS
47 # 0.8.0 - added sys.version parser and various new access
48 # APIs (python_version(), python_compiler(), etc.)
49 # 0.7.2 - fixed architecture() to use sizeof(pointer) where available
50 # 0.7.1 - added support for Caldera OpenLinux
51 # 0.7.0 - some fixes for WinCE; untabified the source file
52 # 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
53 # vms_lib.getsyi() configured
54 # 0.6.1 - added code to prevent 'uname -p' on platforms which are
55 # known not to support it
56 # 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
57 # did some cleanup of the interfaces - some APIs have changed
58 # 0.5.5 - fixed another type in the MacOS code... should have
59 # used more coffee today ;-)
60 # 0.5.4 - fixed a few typos in the MacOS code
61 # 0.5.3 - added experimental MacOS support; added better popen()
62 # workarounds in _syscmd_ver() -- still not 100% elegant
63 # though
64 # 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
65 # return values (the system uname command tends to return
66 # 'unknown' instead of just leaving the field empty)
67 # 0.5.1 - included code for slackware dist; added exception handlers
68 # to cover up situations where platforms don't have os.popen
69 # (e.g. Mac) or fail on socket.gethostname(); fixed libc
70 # detection RE
71 # 0.5.0 - changed the API names referring to system commands to *syscmd*;
72 # added java_ver(); made syscmd_ver() a private
73 # API (was system_ver() in previous versions) -- use uname()
74 # instead; extended the win32_ver() to also return processor
75 # type information
76 # 0.4.0 - added win32_ver() and modified the platform() output for WinXX
77 # 0.3.4 - fixed a bug in _follow_symlinks()
78 # 0.3.3 - fixed popen() and "file" command invokation bugs
79 # 0.3.2 - added architecture() API and support for it in platform()
80 # 0.3.1 - fixed syscmd_ver() RE to support Windows NT
81 # 0.3.0 - added system alias support
82 # 0.2.3 - removed 'wince' again... oh well.
83 # 0.2.2 - added 'wince' to syscmd_ver() supported platforms
84 # 0.2.1 - added cache logic and changed the platform string format
85 # 0.2.0 - changed the API to use functions instead of module globals
86 # since some action take too long to be run on module import
87 # 0.1.0 - first release
88 #
89 # You can always get the latest version of this module at:
90 #
91 # http://www.egenix.com/files/python/platform.py
92 #
93 # If that URL should fail, try contacting the author.
94
95 __copyright__ = """
96 Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:[email protected]
97 Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:[email protected]
98
99 Permission to use, copy, modify, and distribute this software and its
100 documentation for any purpose and without fee or royalty is hereby granted,
101 provided that the above copyright notice appear in all copies and that
102 both that copyright notice and this permission notice appear in
103 supporting documentation or portions thereof, including modifications,
104 that you make.
105
106 EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
107 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
108 FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
109 INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
110 FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
111 NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
112 WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
113
114 """
115
116 __version__ = '1.0.7'
117
118 import sys,string,os,re
119
120 ### Globals & Constants
121
122 # Determine the platform's /dev/null device
123 try:
124 DEV_NULL = os.devnull
125 except AttributeError:
126 # os.devnull was added in Python 2.4, so emulate it for earlier
127 # Python versions
128 if sys.platform in ('dos','win32','win16','os2'):
129 # Use the old CP/M NUL as device name
130 DEV_NULL = 'NUL'
131 else:
132 # Standard Unix uses /dev/null
133 DEV_NULL = '/dev/null'
134
135 # Helper for comparing two version number strings.
136 # Based on the description of the PHP's version_compare():
137 # http://php.net/manual/en/function.version-compare.php
138
139 _ver_stages = {
140 # any string not found in this dict, will get 0 assigned
141 'dev': 10,
142 'alpha': 20, 'a': 20,
143 'beta': 30, 'b': 30,
144 'c': 40,
145 'RC': 50, 'rc': 50,
146 # number, will get 100 assigned
147 'pl': 200, 'p': 200,
148 }
149
150 _component_re = re.compile(r'([0-9]+|[._+-])')
151
152 def _comparable_version(version):
153 result = []
154 for v in _component_re.split(version):
155 if v not in '._+-':
156 try:
157 v = int(v, 10)
158 t = 100
159 except ValueError:
160 t = _ver_stages.get(v, 0)
161 result.extend((t, v))
162 return result
163
164 ### Platform specific APIs
165
166 _libc_search = re.compile(r'(__libc_init)'
167 '|'
168 '(GLIBC_([0-9.]+))'
169 '|'
170 '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
171
172 def libc_ver(executable=sys.executable,lib='',version='', chunksize=2048):
173
174 """ Tries to determine the libc version that the file executable
175 (which defaults to the Python interpreter) is linked against.
176
177 Returns a tuple of strings (lib,version) which default to the
178 given parameters in case the lookup fails.
179
180 Note that the function has intimate knowledge of how different
181 libc versions add symbols to the executable and thus is probably
182 only useable for executables compiled using gcc.
183
184 The file is read and scanned in chunks of chunksize bytes.
185
186 """
187 V = _comparable_version
188 if hasattr(os.path, 'realpath'):
189 # Python 2.2 introduced os.path.realpath(); it is used
190 # here to work around problems with Cygwin not being
191 # able to open symlinks for reading
192 executable = os.path.realpath(executable)
193 with open(executable, 'rb') as f:
194 binary = f.read(chunksize)
195 pos = 0
196 while pos < len(binary):
197 if 'libc' in binary or 'GLIBC' in binary:
198 m = _libc_search.search(binary, pos)
199 else:
200 m = None
201 if not m or m.end() == len(binary):
202 chunk = f.read(chunksize)
203 if chunk:
204 binary = binary[max(pos, len(binary) - 1000):] + chunk
205 pos = 0
206 continue
207 if not m:
208 break
209 libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
210 if libcinit and not lib:
211 lib = 'libc'
212 elif glibc:
213 if lib != 'glibc':
214 lib = 'glibc'
215 version = glibcversion
216 elif V(glibcversion) > V(version):
217 version = glibcversion
218 elif so:
219 if lib != 'glibc':
220 lib = 'libc'
221 if soversion and (not version or V(soversion) > V(version)):
222 version = soversion
223 if threads and version[-len(threads):] != threads:
224 version = version + threads
225 pos = m.end()
226 return lib,version
227
228 def _dist_try_harder(distname,version,id):
229
230 """ Tries some special tricks to get the distribution
231 information in case the default method fails.
232
233 Currently supports older SuSE Linux, Caldera OpenLinux and
234 Slackware Linux distributions.
235
236 """
237 if os.path.exists('/var/adm/inst-log/info'):
238 # SuSE Linux stores distribution information in that file
239 info = open('/var/adm/inst-log/info').readlines()
240 distname = 'SuSE'
241 for line in info:
242 tv = string.split(line)
243 if len(tv) == 2:
244 tag,value = tv
245 else:
246 continue
247 if tag == 'MIN_DIST_VERSION':
248 version = string.strip(value)
249 elif tag == 'DIST_IDENT':
250 values = string.split(value,'-')
251 id = values[2]
252 return distname,version,id
253
254 if os.path.exists('/etc/.installed'):
255 # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
256 info = open('/etc/.installed').readlines()
257 for line in info:
258 pkg = string.split(line,'-')
259 if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
260 # XXX does Caldera support non Intel platforms ? If yes,
261 # where can we find the needed id ?
262 return 'OpenLinux',pkg[1],id
263
264 if os.path.isdir('/usr/lib/setup'):
265 # Check for slackware version tag file (thanks to Greg Andruk)
266 verfiles = os.listdir('/usr/lib/setup')
267 for n in range(len(verfiles)-1, -1, -1):
268 if verfiles[n][:14] != 'slack-version-':
269 del verfiles[n]
270 if verfiles:
271 verfiles.sort()
272 distname = 'slackware'
273 version = verfiles[-1][14:]
274 return distname,version,id
275
276 return distname,version,id
277
278 _release_filename = re.compile(r'(\w+)[-_](release|version)')
279 _lsb_release_version = re.compile(r'(.+)'
280 ' release '
281 '([\d.]+)'
282 '[^(]*(?:\((.+)\))?')
283 _release_version = re.compile(r'([^0-9]+)'
284 '(?: release )?'
285 '([\d.]+)'
286 '[^(]*(?:\((.+)\))?')
287
288 # See also http://www.novell.com/coolsolutions/feature/11251.html
289 # and http://linuxmafia.com/faq/Admin/release-files.html
290 # and http://data.linux-ntfs.org/rpm/whichrpm
291 # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
292
293 _supported_dists = (
294 'SuSE', 'debian', 'fedora', 'redhat', 'centos',
295 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
296 'UnitedLinux', 'turbolinux')
297
298 def _parse_release_file(firstline):
299
300 # Default to empty 'version' and 'id' strings. Both defaults are used
301 # when 'firstline' is empty. 'id' defaults to empty when an id can not
302 # be deduced.
303 version = ''
304 id = ''
305
306 # Parse the first line
307 m = _lsb_release_version.match(firstline)
308 if m is not None:
309 # LSB format: "distro release x.x (codename)"
310 return tuple(m.groups())
311
312 # Pre-LSB format: "distro x.x (codename)"
313 m = _release_version.match(firstline)
314 if m is not None:
315 return tuple(m.groups())
316
317 # Unknown format... take the first two words
318 l = string.split(string.strip(firstline))
319 if l:
320 version = l[0]
321 if len(l) > 1:
322 id = l[1]
323 return '', version, id
324
325 def linux_distribution(distname='', version='', id='',
326
327 supported_dists=_supported_dists,
328 full_distribution_name=1):
329
330 """ Tries to determine the name of the Linux OS distribution name.
331
332 The function first looks for a distribution release file in
333 /etc and then reverts to _dist_try_harder() in case no
334 suitable files are found.
335
336 supported_dists may be given to define the set of Linux
337 distributions to look for. It defaults to a list of currently
338 supported Linux distributions identified by their release file
339 name.
340
341 If full_distribution_name is true (default), the full
342 distribution read from the OS is returned. Otherwise the short
343 name taken from supported_dists is used.
344
345 Returns a tuple (distname,version,id) which default to the
346 args given as parameters.
347
348 """
349 try:
350 etc = os.listdir('/etc')
351 except os.error:
352 # Probably not a Unix system
353 return distname,version,id
354 etc.sort()
355 for file in etc:
356 m = _release_filename.match(file)
357 if m is not None:
358 _distname,dummy = m.groups()
359 if _distname in supported_dists:
360 distname = _distname
361 break
362 else:
363 return _dist_try_harder(distname,version,id)
364
365 # Read the first line
366 f = open('/etc/'+file, 'r')
367 firstline = f.readline()
368 f.close()
369 _distname, _version, _id = _parse_release_file(firstline)
370
371 if _distname and full_distribution_name:
372 distname = _distname
373 if _version:
374 version = _version
375 if _id:
376 id = _id
377 return distname, version, id
378
379 # To maintain backwards compatibility:
380
381 def dist(distname='',version='',id='',
382
383 supported_dists=_supported_dists):
384
385 """ Tries to determine the name of the Linux OS distribution name.
386
387 The function first looks for a distribution release file in
388 /etc and then reverts to _dist_try_harder() in case no
389 suitable files are found.
390
391 Returns a tuple (distname,version,id) which default to the
392 args given as parameters.
393
394 """
395 return linux_distribution(distname, version, id,
396 supported_dists=supported_dists,
397 full_distribution_name=0)
398
399 class _popen:
400
401 """ Fairly portable (alternative) popen implementation.
402
403 This is mostly needed in case os.popen() is not available, or
404 doesn't work as advertised, e.g. in Win9X GUI programs like
405 PythonWin or IDLE.
406
407 Writing to the pipe is currently not supported.
408
409 """
410 tmpfile = ''
411 pipe = None
412 bufsize = None
413 mode = 'r'
414
415 def __init__(self,cmd,mode='r',bufsize=None):
416
417 if mode != 'r':
418 raise ValueError,'popen()-emulation only supports read mode'
419 import tempfile
420 self.tmpfile = tmpfile = tempfile.mktemp()
421 os.system(cmd + ' > %s' % tmpfile)
422 self.pipe = open(tmpfile,'rb')
423 self.bufsize = bufsize
424 self.mode = mode
425
426 def read(self):
427
428 return self.pipe.read()
429
430 def readlines(self):
431
432 if self.bufsize is not None:
433 return self.pipe.readlines()
434
435 def close(self,
436
437 remove=os.unlink,error=os.error):
438
439 if self.pipe:
440 rc = self.pipe.close()
441 else:
442 rc = 255
443 if self.tmpfile:
444 try:
445 remove(self.tmpfile)
446 except error:
447 pass
448 return rc
449
450 # Alias
451 __del__ = close
452
453 def popen(cmd, mode='r', bufsize=None):
454
455 """ Portable popen() interface.
456 """
457 # Find a working popen implementation preferring win32pipe.popen
458 # over os.popen over _popen
459 popen = None
460 if os.environ.get('OS','') == 'Windows_NT':
461 # On NT win32pipe should work; on Win9x it hangs due to bugs
462 # in the MS C lib (see MS KnowledgeBase article Q150956)
463 try:
464 import win32pipe
465 except ImportError:
466 pass
467 else:
468 popen = win32pipe.popen
469 if popen is None:
470 if hasattr(os,'popen'):
471 popen = os.popen
472 # Check whether it works... it doesn't in GUI programs
473 # on Windows platforms
474 if sys.platform == 'win32': # XXX Others too ?
475 try:
476 popen('')
477 except os.error:
478 popen = _popen
479 else:
480 popen = _popen
481 if bufsize is None:
482 return popen(cmd,mode)
483 else:
484 return popen(cmd,mode,bufsize)
485
486
487 def _norm_version(version, build=''):
488
489 """ Normalize the version and build strings and return a single
490 version string using the format major.minor.build (or patchlevel).
491 """
492 l = string.split(version,'.')
493 if build:
494 l.append(build)
495 try:
496 ints = map(int,l)
497 except ValueError:
498 strings = l
499 else:
500 strings = map(str,ints)
501 version = string.join(strings[:3],'.')
502 return version
503
504 _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
505 '.*'
506 '\[.* ([\d.]+)\])')
507
508 # Examples of VER command output:
509 #
510 # Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
511 # Windows XP: Microsoft Windows XP [Version 5.1.2600]
512 # Windows Vista: Microsoft Windows [Version 6.0.6002]
513 #
514 # Note that the "Version" string gets localized on different
515 # Windows versions.
516
517 def _syscmd_ver(system='', release='', version='',
518
519 supported_platforms=('win32','win16','dos','os2')):
520
521 """ Tries to figure out the OS version used and returns
522 a tuple (system,release,version).
523
524 It uses the "ver" shell command for this which is known
525 to exists on Windows, DOS and OS/2. XXX Others too ?
526
527 In case this fails, the given parameters are used as
528 defaults.
529
530 """
531 if sys.platform not in supported_platforms:
532 return system,release,version
533
534 # Try some common cmd strings
535 for cmd in ('ver','command /c ver','cmd /c ver'):
536 try:
537 pipe = popen(cmd)
538 info = pipe.read()
539 if pipe.close():
540 raise os.error,'command failed'
541 # XXX How can I suppress shell errors from being written
542 # to stderr ?
543 except os.error,why:
544 #print 'Command %s failed: %s' % (cmd,why)
545 continue
546 except IOError,why:
547 #print 'Command %s failed: %s' % (cmd,why)
548 continue
549 else:
550 break
551 else:
552 return system,release,version
553
554 # Parse the output
555 info = string.strip(info)
556 m = _ver_output.match(info)
557 if m is not None:
558 system,release,version = m.groups()
559 # Strip trailing dots from version and release
560 if release[-1] == '.':
561 release = release[:-1]
562 if version[-1] == '.':
563 version = version[:-1]
564 # Normalize the version and build strings (eliminating additional
565 # zeros)
566 version = _norm_version(version)
567 return system,release,version
568
569 _WIN32_CLIENT_RELEASES = {
570 (5, 0): "2000",
571 (5, 1): "XP",
572 # Strictly, 5.2 client is XP 64-bit, but platform.py historically
573 # has always called it 2003 Server
574 (5, 2): "2003Server",
575 (5, None): "post2003",
576
577 (6, 0): "Vista",
578 (6, 1): "7",
579 (6, 2): "8",
580 (6, 3): "8.1",
581 (6, None): "post8.1",
582
583 (10, 0): "10",
584 (10, None): "post10",
585 }
586
587 # Server release name lookup will default to client names if necessary
588 _WIN32_SERVER_RELEASES = {
589 (5, 2): "2003Server",
590
591 (6, 0): "2008Server",
592 (6, 1): "2008ServerR2",
593 (6, 2): "2012Server",
594 (6, 3): "2012ServerR2",
595 (6, None): "post2012ServerR2",
596 }
597
598 def _get_real_winver(maj, min, build):
599 if maj < 6 or (maj == 6 and min < 2):
600 return maj, min, build
601
602 from ctypes import (c_buffer, POINTER, byref, create_unicode_buffer,
603 Structure, WinDLL, _Pointer)
604 from ctypes.wintypes import DWORD, HANDLE
605
606 class VS_FIXEDFILEINFO(Structure):
607 _fields_ = [
608 ("dwSignature", DWORD),
609 ("dwStrucVersion", DWORD),
610 ("dwFileVersionMS", DWORD),
611 ("dwFileVersionLS", DWORD),
612 ("dwProductVersionMS", DWORD),
613 ("dwProductVersionLS", DWORD),
614 ("dwFileFlagsMask", DWORD),
615 ("dwFileFlags", DWORD),
616 ("dwFileOS", DWORD),
617 ("dwFileType", DWORD),
618 ("dwFileSubtype", DWORD),
619 ("dwFileDateMS", DWORD),
620 ("dwFileDateLS", DWORD),
621 ]
622 class PVS_FIXEDFILEINFO(_Pointer):
623 _type_ = VS_FIXEDFILEINFO
624
625 kernel32 = WinDLL('kernel32')
626 version = WinDLL('version')
627
628 # We will immediately double the length up to MAX_PATH, but the
629 # path may be longer, so we retry until the returned string is
630 # shorter than our buffer.
631 name_len = actual_len = 130
632 while actual_len == name_len:
633 name_len *= 2
634 name = create_unicode_buffer(name_len)
635 actual_len = kernel32.GetModuleFileNameW(HANDLE(kernel32._handle),
636 name, len(name))
637 if not actual_len:
638 return maj, min, build
639
640 size = version.GetFileVersionInfoSizeW(name, None)
641 if not size:
642 return maj, min, build
643
644 ver_block = c_buffer(size)
645 if (not version.GetFileVersionInfoW(name, None, size, ver_block) or
646 not ver_block):
647 return maj, min, build
648
649 pvi = PVS_FIXEDFILEINFO()
650 if not version.VerQueryValueW(ver_block, "", byref(pvi), byref(DWORD())):
651 return maj, min, build
652
653 maj = pvi.contents.dwProductVersionMS >> 16
654 min = pvi.contents.dwProductVersionMS & 0xFFFF
655 build = pvi.contents.dwProductVersionLS >> 16
656
657 return maj, min, build
658
659 def win32_ver(release='', version='', csd='', ptype=''):
660 try:
661 from sys import getwindowsversion
662 except ImportError:
663 return release, version, csd, ptype
664 try:
665 from winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
666 except ImportError:
667 from _winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
668
669 winver = getwindowsversion()
670 maj, min, build = _get_real_winver(*winver[:3])
671 version = '{0}.{1}.{2}'.format(maj, min, build)
672
673 release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or
674 _WIN32_CLIENT_RELEASES.get((maj, None)) or
675 release)
676
677 # getwindowsversion() reflect the compatibility mode Python is
678 # running under, and so the service pack value is only going to be
679 # valid if the versions match.
680 if winver[:2] == (maj, min):
681 try:
682 csd = 'SP{}'.format(winver.service_pack_major)
683 except AttributeError:
684 if csd[:13] == 'Service Pack ':
685 csd = 'SP' + csd[13:]
686
687 # VER_NT_SERVER = 3
688 if getattr(winver, 'product_type', None) == 3:
689 release = (_WIN32_SERVER_RELEASES.get((maj, min)) or
690 _WIN32_SERVER_RELEASES.get((maj, None)) or
691 release)
692
693 key = None
694 try:
695 key = OpenKeyEx(HKEY_LOCAL_MACHINE,
696 r'SOFTWARE\Microsoft\Windows NT\CurrentVersion')
697 ptype = QueryValueEx(key, 'CurrentType')[0]
698 except:
699 pass
700 finally:
701 if key:
702 CloseKey(key)
703
704 return release, version, csd, ptype
705
706 def _mac_ver_lookup(selectors,default=None):
707
708 from gestalt import gestalt
709 import MacOS
710 l = []
711 append = l.append
712 for selector in selectors:
713 try:
714 append(gestalt(selector))
715 except (RuntimeError, MacOS.Error):
716 append(default)
717 return l
718
719 def _bcd2str(bcd):
720
721 return hex(bcd)[2:]
722
723 def _mac_ver_gestalt():
724 """
725 Thanks to Mark R. Levinson for mailing documentation links and
726 code examples for this function. Documentation for the
727 gestalt() API is available online at:
728
729 http://www.rgaros.nl/gestalt/
730 """
731 # Check whether the version info module is available
732 try:
733 import gestalt
734 import MacOS
735 except ImportError:
736 return None
737 # Get the infos
738 sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
739 # Decode the infos
740 if sysv:
741 major = (sysv & 0xFF00) >> 8
742 minor = (sysv & 0x00F0) >> 4
743 patch = (sysv & 0x000F)
744
745 if (major, minor) >= (10, 4):
746 # the 'sysv' gestald cannot return patchlevels
747 # higher than 9. Apple introduced 3 new
748 # gestalt codes in 10.4 to deal with this
749 # issue (needed because patch levels can
750 # run higher than 9, such as 10.4.11)
751 major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
752 release = '%i.%i.%i' %(major, minor, patch)
753 else:
754 release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
755
756 if sysa:
757 machine = {0x1: '68k',
758 0x2: 'PowerPC',
759 0xa: 'i386'}.get(sysa,'')
760
761 versioninfo=('', '', '')
762 return release,versioninfo,machine
763
764 def _mac_ver_xml():
765 fn = '/System/Library/CoreServices/SystemVersion.plist'
766 if not os.path.exists(fn):
767 return None
768
769 try:
770 import plistlib
771 except ImportError:
772 return None
773
774 pl = plistlib.readPlist(fn)
775 release = pl['ProductVersion']
776 versioninfo=('', '', '')
777 machine = os.uname()[4]
778 if machine in ('ppc', 'Power Macintosh'):
779 # for compatibility with the gestalt based code
780 machine = 'PowerPC'
781
782 return release,versioninfo,machine
783
784
785 def mac_ver(release='',versioninfo=('','',''),machine=''):
786
787 """ Get MacOS version information and return it as tuple (release,
788 versioninfo, machine) with versioninfo being a tuple (version,
789 dev_stage, non_release_version).
790
791 Entries which cannot be determined are set to the parameter values
792 which default to ''. All tuple entries are strings.
793 """
794
795 # First try reading the information from an XML file which should
796 # always be present
797 info = _mac_ver_xml()
798 if info is not None:
799 return info
800
801 # If that doesn't work for some reason fall back to reading the
802 # information using gestalt calls.
803 info = _mac_ver_gestalt()
804 if info is not None:
805 return info
806
807 # If that also doesn't work return the default values
808 return release,versioninfo,machine
809
810 def _java_getprop(name,default):
811
812 from java.lang import System
813 try:
814 value = System.getProperty(name)
815 if value is None:
816 return default
817 return value
818 except AttributeError:
819 return default
820
821 def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
822
823 """ Version interface for Jython.
824
825 Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
826 a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
827 tuple (os_name,os_version,os_arch).
828
829 Values which cannot be determined are set to the defaults
830 given as parameters (which all default to '').
831
832 """
833 # Import the needed APIs
834 try:
835 import java.lang
836 except ImportError:
837 return release,vendor,vminfo,osinfo
838
839 vendor = _java_getprop('java.vendor', vendor)
840 release = _java_getprop('java.version', release)
841 vm_name, vm_release, vm_vendor = vminfo
842 vm_name = _java_getprop('java.vm.name', vm_name)
843 vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
844 vm_release = _java_getprop('java.vm.version', vm_release)
845 vminfo = vm_name, vm_release, vm_vendor
846 os_name, os_version, os_arch = osinfo
847 os_arch = _java_getprop('java.os.arch', os_arch)
848 os_name = _java_getprop('java.os.name', os_name)
849 os_version = _java_getprop('java.os.version', os_version)
850 osinfo = os_name, os_version, os_arch
851
852 return release, vendor, vminfo, osinfo
853
854 ### System name aliasing
855
856 def system_alias(system,release,version):
857
858 """ Returns (system,release,version) aliased to common
859 marketing names used for some systems.
860
861 It also does some reordering of the information in some cases
862 where it would otherwise cause confusion.
863
864 """
865 if system == 'Rhapsody':
866 # Apple's BSD derivative
867 # XXX How can we determine the marketing release number ?
868 return 'MacOS X Server',system+release,version
869
870 elif system == 'SunOS':
871 # Sun's OS
872 if release < '5':
873 # These releases use the old name SunOS
874 return system,release,version
875 # Modify release (marketing release = SunOS release - 3)
876 l = string.split(release,'.')
877 if l:
878 try:
879 major = int(l[0])
880 except ValueError:
881 pass
882 else:
883 major = major - 3
884 l[0] = str(major)
885 release = string.join(l,'.')
886 if release < '6':
887 system = 'Solaris'
888 else:
889 # XXX Whatever the new SunOS marketing name is...
890 system = 'Solaris'
891
892 elif system == 'IRIX64':
893 # IRIX reports IRIX64 on platforms with 64-bit support; yet it
894 # is really a version and not a different platform, since 32-bit
895 # apps are also supported..
896 system = 'IRIX'
897 if version:
898 version = version + ' (64bit)'
899 else:
900 version = '64bit'
901
902 elif system in ('win32','win16'):
903 # In case one of the other tricks
904 system = 'Windows'
905
906 return system,release,version
907
908 ### Various internal helpers
909
910 def _platform(*args):
911
912 """ Helper to format the platform string in a filename
913 compatible format e.g. "system-version-machine".
914 """
915 # Format the platform string
916 platform = string.join(
917 map(string.strip,
918 filter(len, args)),
919 '-')
920
921 # Cleanup some possible filename obstacles...
922 replace = string.replace
923 platform = replace(platform,' ','_')
924 platform = replace(platform,'/','-')
925 platform = replace(platform,'\\','-')
926 platform = replace(platform,':','-')
927 platform = replace(platform,';','-')
928 platform = replace(platform,'"','-')
929 platform = replace(platform,'(','-')
930 platform = replace(platform,')','-')
931
932 # No need to report 'unknown' information...
933 platform = replace(platform,'unknown','')
934
935 # Fold '--'s and remove trailing '-'
936 while 1:
937 cleaned = replace(platform,'--','-')
938 if cleaned == platform:
939 break
940 platform = cleaned
941 while platform[-1] == '-':
942 platform = platform[:-1]
943
944 return platform
945
946 def _node(default=''):
947
948 """ Helper to determine the node name of this machine.
949 """
950 try:
951 import socket
952 except ImportError:
953 # No sockets...
954 return default
955 try:
956 return socket.gethostname()
957 except socket.error:
958 # Still not working...
959 return default
960
961 # os.path.abspath is new in Python 1.5.2:
962 if not hasattr(os.path,'abspath'):
963
964 def _abspath(path,
965
966 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
967 normpath=os.path.normpath):
968
969 if not isabs(path):
970 path = join(getcwd(), path)
971 return normpath(path)
972
973 else:
974
975 _abspath = os.path.abspath
976
977 def _follow_symlinks(filepath):
978
979 """ In case filepath is a symlink, follow it until a
980 real file is reached.
981 """
982 filepath = _abspath(filepath)
983 while os.path.islink(filepath):
984 filepath = os.path.normpath(
985 os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
986 return filepath
987
988 def _syscmd_uname(option,default=''):
989
990 """ Interface to the system's uname command.
991 """
992 if sys.platform in ('dos','win32','win16','os2'):
993 # XXX Others too ?
994 return default
995 try:
996 f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
997 except (AttributeError,os.error):
998 return default
999 output = string.strip(f.read())
1000 rc = f.close()
1001 if not output or rc:
1002 return default
1003 else:
1004 return output
1005
1006 def _syscmd_file(target,default=''):
1007
1008 """ Interface to the system's file command.
1009
1010 The function uses the -b option of the file command to have it
1011 ommit the filename in its output and if possible the -L option
1012 to have the command follow symlinks. It returns default in
1013 case the command should fail.
1014
1015 """
1016
1017 # We do the import here to avoid a bootstrap issue.
1018 # See c73b90b6dadd changeset.
1019 #
1020 # [..]
1021 # ranlib libpython2.7.a
1022 # gcc -o python \
1023 # Modules/python.o \
1024 # libpython2.7.a -lsocket -lnsl -ldl -lm
1025 # Traceback (most recent call last):
1026 # File "./setup.py", line 8, in <module>
1027 # from platform import machine as platform_machine
1028 # File "[..]/build/Lib/platform.py", line 116, in <module>
1029 # import sys,string,os,re,subprocess
1030 # File "[..]/build/Lib/subprocess.py", line 429, in <module>
1031 # import select
1032 # ImportError: No module named select
1033
1034 import subprocess
1035
1036 if sys.platform in ('dos','win32','win16','os2'):
1037 # XXX Others too ?
1038 return default
1039 target = _follow_symlinks(target)
1040 try:
1041 proc = subprocess.Popen(['file', target],
1042 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
1043
1044 except (AttributeError,os.error):
1045 return default
1046 output = proc.communicate()[0]
1047 rc = proc.wait()
1048 if not output or rc:
1049 return default
1050 else:
1051 return output
1052
1053 ### Information about the used architecture
1054
1055 # Default values for architecture; non-empty strings override the
1056 # defaults given as parameters
1057 _default_architecture = {
1058 'win32': ('','WindowsPE'),
1059 'win16': ('','Windows'),
1060 'dos': ('','MSDOS'),
1061 }
1062
1063 _architecture_split = re.compile(r'[\s,]').split
1064
1065 def architecture(executable=sys.executable,bits='',linkage=''):
1066
1067 """ Queries the given executable (defaults to the Python interpreter
1068 binary) for various architecture information.
1069
1070 Returns a tuple (bits,linkage) which contains information about
1071 the bit architecture and the linkage format used for the
1072 executable. Both values are returned as strings.
1073
1074 Values that cannot be determined are returned as given by the
1075 parameter presets. If bits is given as '', the sizeof(pointer)
1076 (or sizeof(long) on Python version < 1.5.2) is used as
1077 indicator for the supported pointer size.
1078
1079 The function relies on the system's "file" command to do the
1080 actual work. This is available on most if not all Unix
1081 platforms. On some non-Unix platforms where the "file" command
1082 does not exist and the executable is set to the Python interpreter
1083 binary defaults from _default_architecture are used.
1084
1085 """
1086 # Use the sizeof(pointer) as default number of bits if nothing
1087 # else is given as default.
1088 if not bits:
1089 import struct
1090 try:
1091 size = struct.calcsize('P')
1092 except struct.error:
1093 # Older installations can only query longs
1094 size = struct.calcsize('l')
1095 bits = str(size*8) + 'bit'
1096
1097 # Get data from the 'file' system command
1098 if executable:
1099 output = _syscmd_file(executable, '')
1100 else:
1101 output = ''
1102
1103 if not output and \
1104 executable == sys.executable:
1105 # "file" command did not return anything; we'll try to provide
1106 # some sensible defaults then...
1107 if sys.platform in _default_architecture:
1108 b, l = _default_architecture[sys.platform]
1109 if b:
1110 bits = b
1111 if l:
1112 linkage = l
1113 return bits, linkage
1114
1115 # Split the output into a list of strings omitting the filename
1116 fileout = _architecture_split(output)[1:]
1117
1118 if 'executable' not in fileout:
1119 # Format not supported
1120 return bits,linkage
1121
1122 # Bits
1123 if '32-bit' in fileout:
1124 bits = '32bit'
1125 elif 'N32' in fileout:
1126 # On Irix only
1127 bits = 'n32bit'
1128 elif '64-bit' in fileout:
1129 bits = '64bit'
1130
1131 # Linkage
1132 if 'ELF' in fileout:
1133 linkage = 'ELF'
1134 elif 'PE' in fileout:
1135 # E.g. Windows uses this format
1136 if 'Windows' in fileout:
1137 linkage = 'WindowsPE'
1138 else:
1139 linkage = 'PE'
1140 elif 'COFF' in fileout:
1141 linkage = 'COFF'
1142 elif 'MS-DOS' in fileout:
1143 linkage = 'MSDOS'
1144 else:
1145 # XXX the A.OUT format also falls under this class...
1146 pass
1147
1148 return bits,linkage
1149
1150 ### Portable uname() interface
1151
1152 _uname_cache = None
1153
1154 def uname():
1155
1156 """ Fairly portable uname interface. Returns a tuple
1157 of strings (system,node,release,version,machine,processor)
1158 identifying the underlying platform.
1159
1160 Note that unlike the os.uname function this also returns
1161 possible processor information as an additional tuple entry.
1162
1163 Entries which cannot be determined are set to ''.
1164
1165 """
1166 global _uname_cache
1167 no_os_uname = 0
1168
1169 if _uname_cache is not None:
1170 return _uname_cache
1171
1172 processor = ''
1173
1174 # Get some infos from the builtin os.uname API...
1175 try:
1176 system,node,release,version,machine = os.uname()
1177 except AttributeError:
1178 no_os_uname = 1
1179
1180 if no_os_uname or not filter(None, (system, node, release, version, machine)):
1181 # Hmm, no there is either no uname or uname has returned
1182 #'unknowns'... we'll have to poke around the system then.
1183 if no_os_uname:
1184 system = sys.platform
1185 release = ''
1186 version = ''
1187 node = _node()
1188 machine = ''
1189
1190 use_syscmd_ver = 1
1191
1192 # Try win32_ver() on win32 platforms
1193 if system == 'win32':
1194 release,version,csd,ptype = win32_ver()
1195 if release and version:
1196 use_syscmd_ver = 0
1197 # Try to use the PROCESSOR_* environment variables
1198 # available on Win XP and later; see
1199 # http://support.microsoft.com/kb/888731 and
1200 # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
1201 if not machine:
1202 # WOW64 processes mask the native architecture
1203 if "PROCESSOR_ARCHITEW6432" in os.environ:
1204 machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
1205 else:
1206 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
1207 if not processor:
1208 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
1209
1210 # Try the 'ver' system command available on some
1211 # platforms
1212 if use_syscmd_ver:
1213 system,release,version = _syscmd_ver(system)
1214 # Normalize system to what win32_ver() normally returns
1215 # (_syscmd_ver() tends to return the vendor name as well)
1216 if system == 'Microsoft Windows':
1217 system = 'Windows'
1218 elif system == 'Microsoft' and release == 'Windows':
1219 # Under Windows Vista and Windows Server 2008,
1220 # Microsoft changed the output of the ver command. The
1221 # release is no longer printed. This causes the
1222 # system and release to be misidentified.
1223 system = 'Windows'
1224 if '6.0' == version[:3]:
1225 release = 'Vista'
1226 else:
1227 release = ''
1228
1229 # In case we still don't know anything useful, we'll try to
1230 # help ourselves
1231 if system in ('win32','win16'):
1232 if not version:
1233 if system == 'win32':
1234 version = '32bit'
1235 else:
1236 version = '16bit'
1237 system = 'Windows'
1238
1239 elif system[:4] == 'java':
1240 release,vendor,vminfo,osinfo = java_ver()
1241 system = 'Java'
1242 version = string.join(vminfo,', ')
1243 if not version:
1244 version = vendor
1245
1246 # System specific extensions
1247 if system == 'OpenVMS':
1248 # OpenVMS seems to have release and version mixed up
1249 if not release or release == '0':
1250 release = version
1251 version = ''
1252 # Get processor information
1253 try:
1254 import vms_lib
1255 except ImportError:
1256 pass
1257 else:
1258 csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
1259 if (cpu_number >= 128):
1260 processor = 'Alpha'
1261 else:
1262 processor = 'VAX'
1263 if not processor:
1264 # Get processor information from the uname system command
1265 processor = _syscmd_uname('-p','')
1266
1267 #If any unknowns still exist, replace them with ''s, which are more portable
1268 if system == 'unknown':
1269 system = ''
1270 if node == 'unknown':
1271 node = ''
1272 if release == 'unknown':
1273 release = ''
1274 if version == 'unknown':
1275 version = ''
1276 if machine == 'unknown':
1277 machine = ''
1278 if processor == 'unknown':
1279 processor = ''
1280
1281 # normalize name
1282 if system == 'Microsoft' and release == 'Windows':
1283 system = 'Windows'
1284 release = 'Vista'
1285
1286 _uname_cache = system,node,release,version,machine,processor
1287 return _uname_cache
1288
1289 ### Direct interfaces to some of the uname() return values
1290
1291 def system():
1292
1293 """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
1294
1295 An empty string is returned if the value cannot be determined.
1296
1297 """
1298 return uname()[0]
1299
1300 def node():
1301
1302 """ Returns the computer's network name (which may not be fully
1303 qualified)
1304
1305 An empty string is returned if the value cannot be determined.
1306
1307 """
1308 return uname()[1]
1309
1310 def release():
1311
1312 """ Returns the system's release, e.g. '2.2.0' or 'NT'
1313
1314 An empty string is returned if the value cannot be determined.
1315
1316 """
1317 return uname()[2]
1318
1319 def version():
1320
1321 """ Returns the system's release version, e.g. '#3 on degas'
1322
1323 An empty string is returned if the value cannot be determined.
1324
1325 """
1326 return uname()[3]
1327
1328 def machine():
1329
1330 """ Returns the machine type, e.g. 'i386'
1331
1332 An empty string is returned if the value cannot be determined.
1333
1334 """
1335 return uname()[4]
1336
1337 def processor():
1338
1339 """ Returns the (true) processor name, e.g. 'amdk6'
1340
1341 An empty string is returned if the value cannot be
1342 determined. Note that many platforms do not provide this
1343 information or simply return the same value as for machine(),
1344 e.g. NetBSD does this.
1345
1346 """
1347 return uname()[5]
1348
1349 ### Various APIs for extracting information from sys.version
1350
1351 _sys_version_parser = re.compile(
1352 r'([\w.+]+)\s*' # "version<space>"
1353 r'\(#?([^,]+)' # "(#buildno"
1354 r'(?:,\s*([\w ]*)' # ", builddate"
1355 r'(?:,\s*([\w :]*))?)?\)\s*' # ", buildtime)<space>"
1356 r'\[([^\]]+)\]?') # "[compiler]"
1357
1358 _ironpython_sys_version_parser = re.compile(
1359 r'IronPython\s*'
1360 '([\d\.]+)'
1361 '(?: \(([\d\.]+)\))?'
1362 ' on (.NET [\d\.]+)')
1363
1364 # IronPython covering 2.6 and 2.7
1365 _ironpython26_sys_version_parser = re.compile(
1366 r'([\d.]+)\s*'
1367 '\(IronPython\s*'
1368 '[\d.]+\s*'
1369 '\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
1370 )
1371
1372 _pypy_sys_version_parser = re.compile(
1373 r'([\w.+]+)\s*'
1374 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
1375 '\[PyPy [^\]]+\]?')
1376
1377 _sys_version_cache = {}
1378
1379 def _sys_version(sys_version=None):
1380
1381 """ Returns a parsed version of Python's sys.version as tuple
1382 (name, version, branch, revision, buildno, builddate, compiler)
1383 referring to the Python implementation name, version, branch,
1384 revision, build number, build date/time as string and the compiler
1385 identification string.
1386
1387 Note that unlike the Python sys.version, the returned value
1388 for the Python version will always include the patchlevel (it
1389 defaults to '.0').
1390
1391 The function returns empty strings for tuple entries that
1392 cannot be determined.
1393
1394 sys_version may be given to parse an alternative version
1395 string, e.g. if the version was read from a different Python
1396 interpreter.
1397
1398 """
1399 # Get the Python version
1400 if sys_version is None:
1401 sys_version = sys.version
1402
1403 # Try the cache first
1404 result = _sys_version_cache.get(sys_version, None)
1405 if result is not None:
1406 return result
1407
1408 # Parse it
1409 if 'IronPython' in sys_version:
1410 # IronPython
1411 name = 'IronPython'
1412 if sys_version.startswith('IronPython'):
1413 match = _ironpython_sys_version_parser.match(sys_version)
1414 else:
1415 match = _ironpython26_sys_version_parser.match(sys_version)
1416
1417 if match is None:
1418 raise ValueError(
1419 'failed to parse IronPython sys.version: %s' %
1420 repr(sys_version))
1421
1422 version, alt_version, compiler = match.groups()
1423 buildno = ''
1424 builddate = ''
1425
1426 elif sys.platform.startswith('java'):
1427 # Jython
1428 name = 'Jython'
1429 match = _sys_version_parser.match(sys_version)
1430 if match is None:
1431 raise ValueError(
1432 'failed to parse Jython sys.version: %s' %
1433 repr(sys_version))
1434 version, buildno, builddate, buildtime, _ = match.groups()
1435 if builddate is None:
1436 builddate = ''
1437 compiler = sys.platform
1438
1439 elif "PyPy" in sys_version:
1440 # PyPy
1441 name = "PyPy"
1442 match = _pypy_sys_version_parser.match(sys_version)
1443 if match is None:
1444 raise ValueError("failed to parse PyPy sys.version: %s" %
1445 repr(sys_version))
1446 version, buildno, builddate, buildtime = match.groups()
1447 compiler = ""
1448
1449 else:
1450 # CPython
1451 match = _sys_version_parser.match(sys_version)
1452 if match is None:
1453 raise ValueError(
1454 'failed to parse CPython sys.version: %s' %
1455 repr(sys_version))
1456 version, buildno, builddate, buildtime, compiler = \
1457 match.groups()
1458 name = 'CPython'
1459 if builddate is None:
1460 builddate = ''
1461 elif buildtime:
1462 builddate = builddate + ' ' + buildtime
1463
1464 if hasattr(sys, 'subversion'):
1465 # sys.subversion was added in Python 2.5
1466 _, branch, revision = sys.subversion
1467 else:
1468 branch = ''
1469 revision = ''
1470
1471 # Add the patchlevel version if missing
1472 l = string.split(version, '.')
1473 if len(l) == 2:
1474 l.append('0')
1475 version = string.join(l, '.')
1476
1477 # Build and cache the result
1478 result = (name, version, branch, revision, buildno, builddate, compiler)
1479 _sys_version_cache[sys_version] = result
1480 return result
1481
1482 def python_implementation():
1483
1484 """ Returns a string identifying the Python implementation.
1485
1486 Currently, the following implementations are identified:
1487 'CPython' (C implementation of Python),
1488 'IronPython' (.NET implementation of Python),
1489 'Jython' (Java implementation of Python),
1490 'PyPy' (Python implementation of Python).
1491
1492 """
1493 return _sys_version()[0]
1494
1495 def python_version():
1496
1497 """ Returns the Python version as string 'major.minor.patchlevel'
1498
1499 Note that unlike the Python sys.version, the returned value
1500 will always include the patchlevel (it defaults to 0).
1501
1502 """
1503 return _sys_version()[1]
1504
1505 def python_version_tuple():
1506
1507 """ Returns the Python version as tuple (major, minor, patchlevel)
1508 of strings.
1509
1510 Note that unlike the Python sys.version, the returned value
1511 will always include the patchlevel (it defaults to 0).
1512
1513 """
1514 return tuple(string.split(_sys_version()[1], '.'))
1515
1516 def python_branch():
1517
1518 """ Returns a string identifying the Python implementation
1519 branch.
1520
1521 For CPython this is the Subversion branch from which the
1522 Python binary was built.
1523
1524 If not available, an empty string is returned.
1525
1526 """
1527
1528 return _sys_version()[2]
1529
1530 def python_revision():
1531
1532 """ Returns a string identifying the Python implementation
1533 revision.
1534
1535 For CPython this is the Subversion revision from which the
1536 Python binary was built.
1537
1538 If not available, an empty string is returned.
1539
1540 """
1541 return _sys_version()[3]
1542
1543 def python_build():
1544
1545 """ Returns a tuple (buildno, builddate) stating the Python
1546 build number and date as strings.
1547
1548 """
1549 return _sys_version()[4:6]
1550
1551 def python_compiler():
1552
1553 """ Returns a string identifying the compiler used for compiling
1554 Python.
1555
1556 """
1557 return _sys_version()[6]
1558
1559 ### The Opus Magnum of platform strings :-)
1560
1561 _platform_cache = {}
1562
1563 def platform(aliased=0, terse=0):
1564
1565 """ Returns a single string identifying the underlying platform
1566 with as much useful information as possible (but no more :).
1567
1568 The output is intended to be human readable rather than
1569 machine parseable. It may look different on different
1570 platforms and this is intended.
1571
1572 If "aliased" is true, the function will use aliases for
1573 various platforms that report system names which differ from
1574 their common names, e.g. SunOS will be reported as
1575 Solaris. The system_alias() function is used to implement
1576 this.
1577
1578 Setting terse to true causes the function to return only the
1579 absolute minimum information needed to identify the platform.
1580
1581 """
1582 result = _platform_cache.get((aliased, terse), None)
1583 if result is not None:
1584 return result
1585
1586 # Get uname information and then apply platform specific cosmetics
1587 # to it...
1588 system,node,release,version,machine,processor = uname()
1589 if machine == processor:
1590 processor = ''
1591 if aliased:
1592 system,release,version = system_alias(system,release,version)
1593
1594 if system == 'Windows':
1595 # MS platforms
1596 rel,vers,csd,ptype = win32_ver(version)
1597 if terse:
1598 platform = _platform(system,release)
1599 else:
1600 platform = _platform(system,release,version,csd)
1601
1602 elif system in ('Linux',):
1603 # Linux based systems
1604 distname,distversion,distid = dist('')
1605 if distname and not terse:
1606 platform = _platform(system,release,machine,processor,
1607 'with',
1608 distname,distversion,distid)
1609 else:
1610 # If the distribution name is unknown check for libc vs. glibc
1611 libcname,libcversion = libc_ver(sys.executable)
1612 platform = _platform(system,release,machine,processor,
1613 'with',
1614 libcname+libcversion)
1615 elif system == 'Java':
1616 # Java platforms
1617 r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
1618 if terse or not os_name:
1619 platform = _platform(system,release,version)
1620 else:
1621 platform = _platform(system,release,version,
1622 'on',
1623 os_name,os_version,os_arch)
1624
1625 elif system == 'MacOS':
1626 # MacOS platforms
1627 if terse:
1628 platform = _platform(system,release)
1629 else:
1630 platform = _platform(system,release,machine)
1631
1632 else:
1633 # Generic handler
1634 if terse:
1635 platform = _platform(system,release)
1636 else:
1637 bits,linkage = architecture(sys.executable)
1638 platform = _platform(system,release,machine,processor,bits,linkage)
1639
1640 _platform_cache[(aliased, terse)] = platform
1641 return platform
1642
1643 ### Command line interface
1644
1645 if __name__ == '__main__':
1646 # Default is to print the aliased verbose platform string
1647 terse = ('terse' in sys.argv or '--terse' in sys.argv)
1648 aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
1649 print platform(aliased,terse)
1650 sys.exit(0)