blob: 3a4eaaf5377094f48e2514b4ef4b11d0a75a2b4c [file] [log] [blame]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001#!/usr/bin/env python
2
Brett Cannon8ab27df2003-08-05 03:52:04 +00003""" This module tries to retrieve as much platform-identifying data as
Marc-André Lemburg246d8472003-04-24 11:36:11 +00004 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 <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".
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#
Brett Cannon8ab27df2003-08-05 03:52:04 +000023# Many thanks to all those who helped adding platform-specific
Marc-André Lemburg246d8472003-04-24 11:36:11 +000024# 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),
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000031# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
Marc-André Lemburg246d8472003-04-24 11:36:11 +000032#
33# History:
Marc-André Lemburg380f4172005-11-07 16:11:02 +000034#
35# <see CVS and SVN checkin messages for history>
36#
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000037# 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
Marc-André Lemburgcdc79232004-06-19 17:17:00 +000040# 1.0.3 - added normalization of Windows system name
Marc-André Lemburg91e83e22004-03-25 18:35:12 +000041# 1.0.2 - added more Windows support
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +000042# 1.0.1 - reformatted to make doc.py happy
Marc-André Lemburg246d8472003-04-24 11:36:11 +000043# 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
85#
86# You can always get the latest version of this module at:
87#
88# http://www.egenix.com/files/python/platform.py
89#
90# If that URL should fail, try contacting the author.
91
92__copyright__ = """
93 Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000094 Copyright (c) 2000-2007, eGenix.com Software GmbH; mailto:info@egenix.com
Marc-André Lemburg246d8472003-04-24 11:36:11 +000095
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.
102
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 !
110
111"""
112
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000113__version__ = '1.0.6'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000114
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000115import sys, os, re
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000116
117### Platform specific APIs
118
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000119_libc_search = re.compile(r'(__libc_init)'
120 '|'
Tim Peters0eadaac2003-04-24 16:02:54 +0000121 '(GLIBC_([0-9.]+))'
122 '|'
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000123 '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
124
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000125def libc_ver(executable=sys.executable,lib='',version='',
126
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000127 chunksize=2048):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000128
Brett Cannon8ab27df2003-08-05 03:52:04 +0000129 """ Tries to determine the libc version that the file executable
130 (which defaults to the Python interpreter) is linked against.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000131
132 Returns a tuple of strings (lib,version) which default to the
133 given parameters in case the lookup fails.
134
135 Note that the function has intimate knowledge of how different
Brett Cannon8ab27df2003-08-05 03:52:04 +0000136 libc versions add symbols to the executable and thus is probably
137 only useable for executables compiled using gcc.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000138
139 The file is read and scanned in chunks of chunksize bytes.
140
141 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000142 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)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000147 f = open(executable,'rb')
Walter Dörwaldc3b6ac72007-06-07 19:26:24 +0000148 binary = f.read(chunksize).decode('latin-1')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000149 pos = 0
150 while 1:
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000151 m = _libc_search.search(binary,pos)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000152 if not m:
Walter Dörwaldc3b6ac72007-06-07 19:26:24 +0000153 binary = f.read(chunksize).decode('latin-1')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000154 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
177
178def _dist_try_harder(distname,version,id):
179
Tim Peters0eadaac2003-04-24 16:02:54 +0000180 """ Tries some special tricks to get the distribution
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000181 information in case the default method fails.
182
183 Currently supports older SuSE Linux, Caldera OpenLinux and
184 Slackware Linux distributions.
185
186 """
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:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000192 tv = line.split()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000193 if len(tv) == 2:
194 tag,value = tv
195 else:
196 continue
197 if tag == 'MIN_DIST_VERSION':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000198 version = value.strip()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000199 elif tag == 'DIST_IDENT':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000200 values = value.split('-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000201 id = values[2]
202 return distname,version,id
203
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:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000208 pkg = line.split('-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000209 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
213
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')
Guido van Rossum843c7342004-05-04 18:18:59 +0000217 for n in range(len(verfiles)-1, -1, -1):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000218 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
225
226 return distname,version,id
227
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000228_release_filename = re.compile(r'(\w+)[-_](release|version)')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000229_lsb_release_version = re.compile(r'(.+)'
230 ' release '
231 '([\d.]+)'
232 '[^(]*(?:\((.+)\))?')
233_release_version = re.compile(r'([^0-9]+)'
234 '(?: release )?'
235 '([\d.]+)'
236 '[^(]*(?:\((.+)\))?')
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000237
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000238# See also http://www.novell.com/coolsolutions/feature/11251.html
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000239# and http://linuxmafia.com/faq/Admin/release-files.html
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000240# and http://data.linux-ntfs.org/rpm/whichrpm
241# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
Marc-André Lemburg380f4172005-11-07 16:11:02 +0000242
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000243_supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos',
244 'mandrake', 'rocks', 'slackware', 'yellowdog',
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000245 'gentoo', 'UnitedLinux', 'turbolinux')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000246
247def _parse_release_file(firstline):
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000248
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000249 # 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())
254
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())
259
260 # Unkown format... take the first two words
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000261 l = firstline.strip().split()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000262 if l:
263 version = l[0]
264 if len(l) > 1:
265 id = l[1]
266 else:
267 id = ''
268 return '', version, id
269
270def _test_parse_release_file():
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000271
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000272 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'))
283 ):
284 parsed = _parse_release_file(input)
285 if parsed != output:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000286 print((input, parsed))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000287
288def linux_distribution(distname='', version='', id='',
289
290 supported_dists=_supported_dists,
291 full_distribution_name=1):
292
293 """ Tries to determine the name of the Linux OS distribution name.
294
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.
298
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.
303
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.
307
308 Returns a tuple (distname,version,id) which default to the
309 args given as parameters.
310
311 """
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)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000327
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000328 # 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)
333
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
341
342# To maintain backwards compatibility:
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000343
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000344def dist(distname='',version='',id='',
345
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000346 supported_dists=_supported_dists):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000347
Brett Cannon8ab27df2003-08-05 03:52:04 +0000348 """ Tries to determine the name of the Linux OS distribution name.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000349
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.
353
Brett Cannon8ab27df2003-08-05 03:52:04 +0000354 Returns a tuple (distname,version,id) which default to the
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000355 args given as parameters.
356
357 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000358 return linux_distribution(distname, version, id,
359 supported_dists=supported_dists,
360 full_distribution_name=0)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000361
362class _popen:
363
364 """ Fairly portable (alternative) popen implementation.
365
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.
369
370 Writing to the pipe is currently not supported.
371
372 """
373 tmpfile = ''
374 pipe = None
375 bufsize = None
376 mode = 'r'
377
378 def __init__(self,cmd,mode='r',bufsize=None):
379
380 if mode != 'r':
Collin Winterce36ad82007-08-30 01:19:48 +0000381 raise ValueError('popen()-emulation only supports read mode')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000382 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
388
389 def read(self):
390
391 return self.pipe.read()
392
393 def readlines(self):
394
395 if self.bufsize is not None:
396 return self.pipe.readlines()
397
398 def close(self,
399
400 remove=os.unlink,error=os.error):
401
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
412
413 # Alias
414 __del__ = close
415
416def popen(cmd, mode='r', bufsize=None):
417
418 """ Portable popen() interface.
419 """
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)
448
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000449def _norm_version(version, build=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000450
Brett Cannon8ab27df2003-08-05 03:52:04 +0000451 """ Normalize the version and build strings and return a single
Walter Dörwalde5a7fad2005-11-21 17:01:27 +0000452 version string using the format major.minor.build (or patchlevel).
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000453 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000454 l = version.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000455 if build:
456 l.append(build)
457 try:
458 ints = map(int,l)
459 except ValueError:
460 strings = l
461 else:
Neal Norwitz78a70bd2007-08-30 06:16:26 +0000462 strings = list(map(str,ints))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000463 version = '.'.join(strings[:3])
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000464 return version
465
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000466_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
467 '.*'
468 'Version ([\d.]+))')
469
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000470def _syscmd_ver(system='', release='', version='',
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000471
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000472 supported_platforms=('win32','win16','dos','os2')):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000473
474 """ Tries to figure out the OS version used and returns
475 a tuple (system,release,version).
Tim Peters0eadaac2003-04-24 16:02:54 +0000476
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000477 It uses the "ver" shell command for this which is known
478 to exists on Windows, DOS and OS/2. XXX Others too ?
479
480 In case this fails, the given parameters are used as
481 defaults.
482
483 """
484 if sys.platform not in supported_platforms:
485 return system,release,version
486
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():
Collin Winterce36ad82007-08-30 01:19:48 +0000493 raise os.error('command failed')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000494 # XXX How can I supress shell errors from being written
495 # to stderr ?
Guido van Rossumb940e112007-01-10 16:19:56 +0000496 except os.error as why:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000497 #print 'Command %s failed: %s' % (cmd,why)
498 continue
Guido van Rossumb940e112007-01-10 16:19:56 +0000499 except IOError as why:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000500 #print 'Command %s failed: %s' % (cmd,why)
501 continue
502 else:
503 break
504 else:
505 return system,release,version
506
507 # Parse the output
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000508 info = info.strip()
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000509 m = _ver_output.match(info)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000510 if m is not None:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000511 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
521
522def _win32_getvalue(key,name,default=''):
523
524 """ Read a value for name from the registry key.
525
526 In case this fails, default is returned.
527
528 """
529 from win32api import RegQueryValueEx
530 try:
531 return RegQueryValueEx(key,name)
532 except:
533 return default
534
535def win32_ver(release='',version='',csd='',ptype=''):
536
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).
541
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).
548
Andrew M. Kuchling47c2ab62003-04-24 16:36:49 +0000549 Note: this function only works if Mark Hammond's win32
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000550 package is installed and obviously only runs on Win32
551 compatible platforms.
552
553 """
554 # XXX Is there any way to find out the processor type on WinXX ?
555 # XXX Is win32 available on Windows CE ?
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000556 #
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000557 # Adapted from code posted by Karl Putland to comp.lang.python.
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000558 #
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
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000561
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
570
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'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000582 elif min == 10:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000583 release = '98'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000584 elif min == 90:
585 release = 'Me'
586 else:
587 release = 'postMe'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000588 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:
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000595 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'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000603 elif maj == 6:
604 if min == 0:
605 # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx
606 productType = GetVersionEx(1)[8]
607 if productType == 1: # VER_NT_WORKSTATION
608 release = 'Vista'
609 else:
610 release = '2008Server'
611 else:
612 release = 'post2008Server'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000613 else:
614 if not release:
615 # E.g. Win3.1 with win32s
616 release = '%i.%i' % (maj,min)
617 return release,version,csd,ptype
618
619 # Open the registry key
620 try:
621 keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey)
622 # Get a value to make sure the key exists...
623 RegQueryValueEx(keyCurVer,'SystemRoot')
624 except:
625 return release,version,csd,ptype
Tim Peters0eadaac2003-04-24 16:02:54 +0000626
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000627 # Parse values
628 #subversion = _win32_getvalue(keyCurVer,
629 # 'SubVersionNumber',
630 # ('',1))[0]
631 #if subversion:
632 # release = release + subversion # 95a, 95b, etc.
633 build = _win32_getvalue(keyCurVer,
634 'CurrentBuildNumber',
635 ('',1))[0]
636 ptype = _win32_getvalue(keyCurVer,
637 'CurrentType',
638 (ptype,1))[0]
639
640 # Normalize version
641 version = _norm_version(version,build)
642
643 # Close key
644 RegCloseKey(keyCurVer)
645 return release,version,csd,ptype
646
647def _mac_ver_lookup(selectors,default=None):
648
649 from gestalt import gestalt
Jack Jansena290e3d2003-08-11 11:08:49 +0000650 import MacOS
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000651 l = []
652 append = l.append
653 for selector in selectors:
654 try:
655 append(gestalt(selector))
Jack Jansena290e3d2003-08-11 11:08:49 +0000656 except (RuntimeError, MacOS.Error):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000657 append(default)
658 return l
659
660def _bcd2str(bcd):
661
662 return hex(bcd)[2:]
663
664def mac_ver(release='',versioninfo=('','',''),machine=''):
665
666 """ Get MacOS version information and return it as tuple (release,
667 versioninfo, machine) with versioninfo being a tuple (version,
668 dev_stage, non_release_version).
669
Brett Cannon8ab27df2003-08-05 03:52:04 +0000670 Entries which cannot be determined are set to the paramter values
671 which default to ''. All tuple entries are strings.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000672
673 Thanks to Mark R. Levinson for mailing documentation links and
674 code examples for this function. Documentation for the
675 gestalt() API is available online at:
676
677 http://www.rgaros.nl/gestalt/
678
679 """
680 # Check whether the version info module is available
681 try:
682 import gestalt
Jack Jansena290e3d2003-08-11 11:08:49 +0000683 import MacOS
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000684 except ImportError:
685 return release,versioninfo,machine
686 # Get the infos
687 sysv,sysu,sysa = _mac_ver_lookup(('sysv','sysu','sysa'))
688 # Decode the infos
689 if sysv:
690 major = (sysv & 0xFF00) >> 8
691 minor = (sysv & 0x00F0) >> 4
692 patch = (sysv & 0x000F)
693 release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
694 if sysu:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000695 major = int((sysu & 0xFF000000) >> 24)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000696 minor = (sysu & 0x00F00000) >> 20
697 bugfix = (sysu & 0x000F0000) >> 16
698 stage = (sysu & 0x0000FF00) >> 8
699 nonrel = (sysu & 0x000000FF)
700 version = '%s.%i.%i' % (_bcd2str(major),minor,bugfix)
701 nonrel = _bcd2str(nonrel)
702 stage = {0x20:'development',
703 0x40:'alpha',
704 0x60:'beta',
705 0x80:'final'}.get(stage,'')
706 versioninfo = (version,stage,nonrel)
707 if sysa:
Tim Peters0eadaac2003-04-24 16:02:54 +0000708 machine = {0x1: '68k',
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000709 0x2: 'PowerPC',
710 0xa: 'i386'}.get(sysa,'')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000711 return release,versioninfo,machine
712
Neal Norwitz9b924c62003-06-29 04:17:45 +0000713def _java_getprop(name,default):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000714
715 from java.lang import System
716 try:
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000717 value = System.getProperty(name)
718 if value is None:
719 return default
720 return value
721 except AttributeError:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000722 return default
723
724def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
Tim Peters0eadaac2003-04-24 16:02:54 +0000725
Brett Cannon8ab27df2003-08-05 03:52:04 +0000726 """ Version interface for Jython.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000727
728 Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
729 a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
730 tuple (os_name,os_version,os_arch).
731
732 Values which cannot be determined are set to the defaults
733 given as parameters (which all default to '').
734
735 """
736 # Import the needed APIs
737 try:
738 import java.lang
739 except ImportError:
740 return release,vendor,vminfo,osinfo
741
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000742 vendor = _java_getprop('java.vendor', vendor)
743 release = _java_getprop('java.version', release)
744 vm_name, vm_release, vm_vendor = vminfo
745 vm_name = _java_getprop('java.vm.name', vm_name)
746 vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
747 vm_release = _java_getprop('java.vm.version', vm_release)
748 vminfo = vm_name, vm_release, vm_vendor
749 os_name, os_version, os_arch = osinfo
750 os_arch = _java_getprop('java.os.arch', os_arch)
751 os_name = _java_getprop('java.os.name', os_name)
752 os_version = _java_getprop('java.os.version', os_version)
753 osinfo = os_name, os_version, os_arch
Tim Peters0eadaac2003-04-24 16:02:54 +0000754
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000755 return release, vendor, vminfo, osinfo
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000756
757### System name aliasing
758
759def system_alias(system,release,version):
760
761 """ Returns (system,release,version) aliased to common
762 marketing names used for some systems.
763
764 It also does some reordering of the information in some cases
765 where it would otherwise cause confusion.
766
767 """
768 if system == 'Rhapsody':
769 # Apple's BSD derivative
770 # XXX How can we determine the marketing release number ?
771 return 'MacOS X Server',system+release,version
772
773 elif system == 'SunOS':
774 # Sun's OS
775 if release < '5':
776 # These releases use the old name SunOS
777 return system,release,version
778 # Modify release (marketing release = SunOS release - 3)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000779 l = release.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000780 if l:
781 try:
782 major = int(l[0])
783 except ValueError:
784 pass
785 else:
786 major = major - 3
787 l[0] = str(major)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000788 release = '.'.join(l)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000789 if release < '6':
790 system = 'Solaris'
791 else:
792 # XXX Whatever the new SunOS marketing name is...
793 system = 'Solaris'
794
795 elif system == 'IRIX64':
796 # IRIX reports IRIX64 on platforms with 64-bit support; yet it
797 # is really a version and not a different platform, since 32-bit
798 # apps are also supported..
799 system = 'IRIX'
800 if version:
801 version = version + ' (64bit)'
802 else:
803 version = '64bit'
804
805 elif system in ('win32','win16'):
806 # In case one of the other tricks
807 system = 'Windows'
808
809 return system,release,version
810
811### Various internal helpers
812
813def _platform(*args):
814
815 """ Helper to format the platform string in a filename
816 compatible format e.g. "system-version-machine".
817 """
818 # Format the platform string
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000819 platform = '-'.join(x.strip() for x in filter(len, args))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000820
821 # Cleanup some possible filename obstacles...
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000822 platform = platform.replace(' ','_')
823 platform = platform.replace('/','-')
824 platform = platform.replace('\\','-')
825 platform = platform.replace(':','-')
826 platform = platform.replace(';','-')
827 platform = platform.replace('"','-')
828 platform = platform.replace('(','-')
829 platform = platform.replace(')','-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000830
831 # No need to report 'unknown' information...
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000832 platform = platform.replace('unknown','')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000833
834 # Fold '--'s and remove trailing '-'
835 while 1:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000836 cleaned = platform.replace('--','-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000837 if cleaned == platform:
838 break
839 platform = cleaned
840 while platform[-1] == '-':
841 platform = platform[:-1]
842
843 return platform
844
845def _node(default=''):
846
847 """ Helper to determine the node name of this machine.
848 """
849 try:
850 import socket
851 except ImportError:
852 # No sockets...
853 return default
854 try:
855 return socket.gethostname()
856 except socket.error:
857 # Still not working...
858 return default
859
860# os.path.abspath is new in Python 1.5.2:
861if not hasattr(os.path,'abspath'):
862
863 def _abspath(path,
864
865 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
866 normpath=os.path.normpath):
867
868 if not isabs(path):
869 path = join(getcwd(), path)
870 return normpath(path)
871
872else:
873
874 _abspath = os.path.abspath
875
876def _follow_symlinks(filepath):
877
878 """ In case filepath is a symlink, follow it until a
879 real file is reached.
880 """
881 filepath = _abspath(filepath)
882 while os.path.islink(filepath):
883 filepath = os.path.normpath(
884 os.path.join(filepath,os.readlink(filepath)))
885 return filepath
886
887def _syscmd_uname(option,default=''):
888
889 """ Interface to the system's uname command.
890 """
891 if sys.platform in ('dos','win32','win16','os2'):
892 # XXX Others too ?
893 return default
894 try:
895 f = os.popen('uname %s 2> /dev/null' % option)
896 except (AttributeError,os.error):
897 return default
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000898 output = f.read().strip()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000899 rc = f.close()
900 if not output or rc:
901 return default
902 else:
903 return output
904
905def _syscmd_file(target,default=''):
906
907 """ Interface to the system's file command.
908
909 The function uses the -b option of the file command to have it
910 ommit the filename in its output and if possible the -L option
911 to have the command follow symlinks. It returns default in
912 case the command should fail.
913
914 """
915 target = _follow_symlinks(target)
916 try:
917 f = os.popen('file %s 2> /dev/null' % target)
918 except (AttributeError,os.error):
919 return default
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000920 output = f.read().strip()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000921 rc = f.close()
922 if not output or rc:
923 return default
924 else:
925 return output
926
927### Information about the used architecture
928
929# Default values for architecture; non-empty strings override the
930# defaults given as parameters
931_default_architecture = {
932 'win32': ('','WindowsPE'),
933 'win16': ('','Windows'),
934 'dos': ('','MSDOS'),
935}
936
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000937_architecture_split = re.compile(r'[\s,]').split
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000938
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000939def architecture(executable=sys.executable,bits='',linkage=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000940
941 """ Queries the given executable (defaults to the Python interpreter
Brett Cannon8ab27df2003-08-05 03:52:04 +0000942 binary) for various architecture information.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000943
Brett Cannon8ab27df2003-08-05 03:52:04 +0000944 Returns a tuple (bits,linkage) which contains information about
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000945 the bit architecture and the linkage format used for the
946 executable. Both values are returned as strings.
947
948 Values that cannot be determined are returned as given by the
949 parameter presets. If bits is given as '', the sizeof(pointer)
950 (or sizeof(long) on Python version < 1.5.2) is used as
951 indicator for the supported pointer size.
952
953 The function relies on the system's "file" command to do the
954 actual work. This is available on most if not all Unix
Brett Cannon8ab27df2003-08-05 03:52:04 +0000955 platforms. On some non-Unix platforms where the "file" command
956 does not exist and the executable is set to the Python interpreter
957 binary defaults from _default_architecture are used.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000958
959 """
960 # Use the sizeof(pointer) as default number of bits if nothing
961 # else is given as default.
962 if not bits:
963 import struct
964 try:
965 size = struct.calcsize('P')
966 except struct.error:
967 # Older installations can only query longs
968 size = struct.calcsize('l')
969 bits = str(size*8) + 'bit'
Tim Peters0eadaac2003-04-24 16:02:54 +0000970
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000971 # Get data from the 'file' system command
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000972 if executable:
973 output = _syscmd_file(executable, '')
974 else:
975 output = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000976
977 if not output and \
978 executable == sys.executable:
979 # "file" command did not return anything; we'll try to provide
Tim Peters0eadaac2003-04-24 16:02:54 +0000980 # some sensible defaults then...
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000981 if sys.platform in _default_architecture:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000982 b,l = _default_architecture[sys.platform]
983 if b:
984 bits = b
985 if l:
986 linkage = l
987 return bits,linkage
988
989 # Split the output into a list of strings omitting the filename
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000990 fileout = _architecture_split(output)[1:]
Tim Peters0eadaac2003-04-24 16:02:54 +0000991
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000992 if 'executable' not in fileout:
993 # Format not supported
994 return bits,linkage
995
996 # Bits
997 if '32-bit' in fileout:
998 bits = '32bit'
999 elif 'N32' in fileout:
1000 # On Irix only
1001 bits = 'n32bit'
1002 elif '64-bit' in fileout:
1003 bits = '64bit'
1004
1005 # Linkage
1006 if 'ELF' in fileout:
1007 linkage = 'ELF'
1008 elif 'PE' in fileout:
1009 # E.g. Windows uses this format
1010 if 'Windows' in fileout:
1011 linkage = 'WindowsPE'
1012 else:
1013 linkage = 'PE'
1014 elif 'COFF' in fileout:
1015 linkage = 'COFF'
1016 elif 'MS-DOS' in fileout:
1017 linkage = 'MSDOS'
1018 else:
1019 # XXX the A.OUT format also falls under this class...
1020 pass
1021
1022 return bits,linkage
1023
1024### Portable uname() interface
Tim Peters0eadaac2003-04-24 16:02:54 +00001025
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001026_uname_cache = None
1027
1028def uname():
1029
1030 """ Fairly portable uname interface. Returns a tuple
1031 of strings (system,node,release,version,machine,processor)
1032 identifying the underlying platform.
1033
1034 Note that unlike the os.uname function this also returns
Brett Cannon8ab27df2003-08-05 03:52:04 +00001035 possible processor information as an additional tuple entry.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001036
1037 Entries which cannot be determined are set to ''.
1038
1039 """
1040 global _uname_cache
1041
1042 if _uname_cache is not None:
1043 return _uname_cache
1044
1045 # Get some infos from the builtin os.uname API...
1046 try:
1047 system,node,release,version,machine = os.uname()
1048
1049 except AttributeError:
1050 # Hmm, no uname... we'll have to poke around the system then.
1051 system = sys.platform
1052 release = ''
1053 version = ''
1054 node = _node()
1055 machine = ''
1056 processor = ''
1057 use_syscmd_ver = 1
1058
1059 # Try win32_ver() on win32 platforms
1060 if system == 'win32':
1061 release,version,csd,ptype = win32_ver()
1062 if release and version:
1063 use_syscmd_ver = 0
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001064 # XXX Should try to parse the PROCESSOR_* environment variables
1065 # available on Win XP and later; see
1066 # http://support.microsoft.com/kb/888731 and
1067 # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
Tim Peters0eadaac2003-04-24 16:02:54 +00001068
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001069 # Try the 'ver' system command available on some
1070 # platforms
1071 if use_syscmd_ver:
1072 system,release,version = _syscmd_ver(system)
Marc-André Lemburgcdc79232004-06-19 17:17:00 +00001073 # Normalize system to what win32_ver() normally returns
1074 # (_syscmd_ver() tends to return the vendor name as well)
1075 if system == 'Microsoft Windows':
1076 system = 'Windows'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001077 elif system == 'Microsoft' and release == 'Windows':
1078 # Under Windows Vista and Windows Server 2008,
1079 # Microsoft changed the output of the ver command. The
1080 # release is no longer printed. This causes the
1081 # system and release to be misidentified.
1082 system = 'Windows'
1083 if '6.0' == version[:3]:
1084 release = 'Vista'
1085 else:
1086 release = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001087
1088 # In case we still don't know anything useful, we'll try to
1089 # help ourselves
1090 if system in ('win32','win16'):
1091 if not version:
1092 if system == 'win32':
1093 version = '32bit'
1094 else:
1095 version = '16bit'
1096 system = 'Windows'
1097
1098 elif system[:4] == 'java':
1099 release,vendor,vminfo,osinfo = java_ver()
1100 system = 'Java'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001101 version = ', '.join(vminfo)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001102 if not version:
1103 version = vendor
1104
1105 elif os.name == 'mac':
1106 release,(version,stage,nonrel),machine = mac_ver()
1107 system = 'MacOS'
1108
1109 else:
1110 # System specific extensions
1111 if system == 'OpenVMS':
1112 # OpenVMS seems to have release and version mixed up
1113 if not release or release == '0':
1114 release = version
1115 version = ''
1116 # Get processor information
1117 try:
1118 import vms_lib
1119 except ImportError:
1120 pass
1121 else:
1122 csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
1123 if (cpu_number >= 128):
1124 processor = 'Alpha'
1125 else:
1126 processor = 'VAX'
1127 else:
1128 # Get processor information from the uname system command
1129 processor = _syscmd_uname('-p','')
1130
1131 # 'unknown' is not really any useful as information; we'll convert
1132 # it to '' which is more portable
1133 if system == 'unknown':
1134 system = ''
1135 if node == 'unknown':
1136 node = ''
1137 if release == 'unknown':
1138 release = ''
1139 if version == 'unknown':
1140 version = ''
1141 if machine == 'unknown':
1142 machine = ''
1143 if processor == 'unknown':
1144 processor = ''
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
1146 # normalize name
1147 if system == 'Microsoft' and release == 'Windows':
1148 system = 'Windows'
1149 release = 'Vista'
1150
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001151 _uname_cache = system,node,release,version,machine,processor
1152 return _uname_cache
1153
1154### Direct interfaces to some of the uname() return values
1155
1156def system():
1157
1158 """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
1159
1160 An empty string is returned if the value cannot be determined.
1161
1162 """
1163 return uname()[0]
1164
1165def node():
1166
Brett Cannon8ab27df2003-08-05 03:52:04 +00001167 """ Returns the computer's network name (which may not be fully
1168 qualified)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001169
1170 An empty string is returned if the value cannot be determined.
1171
1172 """
1173 return uname()[1]
1174
1175def release():
1176
1177 """ Returns the system's release, e.g. '2.2.0' or 'NT'
1178
1179 An empty string is returned if the value cannot be determined.
1180
1181 """
1182 return uname()[2]
1183
1184def version():
1185
1186 """ Returns the system's release version, e.g. '#3 on degas'
1187
1188 An empty string is returned if the value cannot be determined.
1189
1190 """
1191 return uname()[3]
1192
1193def machine():
1194
1195 """ Returns the machine type, e.g. 'i386'
1196
1197 An empty string is returned if the value cannot be determined.
1198
1199 """
1200 return uname()[4]
1201
1202def processor():
1203
1204 """ Returns the (true) processor name, e.g. 'amdk6'
1205
1206 An empty string is returned if the value cannot be
1207 determined. Note that many platforms do not provide this
1208 information or simply return the same value as for machine(),
1209 e.g. NetBSD does this.
1210
1211 """
1212 return uname()[5]
1213
1214### Various APIs for extracting information from sys.version
1215
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001216_sys_version_parser = re.compile(
1217 r'([\w.+]+)\s*'
1218 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
1219 '\[([^\]]+)\]?')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001220
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001221_jython_sys_version_parser = re.compile(
1222 r'([\d\.]+)')
1223
1224_ironpython_sys_version_parser = re.compile(
1225 r'IronPython\s*'
1226 '([\d\.]+)'
1227 '(?: \(([\d\.]+)\))?'
1228 ' on (.NET [\d\.]+)')
1229
1230_sys_version_cache = {}
1231
1232def _sys_version(sys_version=None):
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001233
1234 """ Returns a parsed version of Python's sys.version as tuple
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001235 (name, version, branch, revision, buildno, builddate, compiler)
1236 referring to the Python implementation name, version, branch,
1237 revision, build number, build date/time as string and the compiler
1238 identification string.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001239
1240 Note that unlike the Python sys.version, the returned value
1241 for the Python version will always include the patchlevel (it
1242 defaults to '.0').
1243
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001244 The function returns empty strings for tuple entries that
1245 cannot be determined.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001246
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001247 sys_version may be given to parse an alternative version
1248 string, e.g. if the version was read from a different Python
1249 interpreter.
1250
1251 """
1252 # Get the Python version
1253 if sys_version is None:
1254 sys_version = sys.version
1255
1256 # Try the cache first
1257 result = _sys_version_cache.get(sys_version, None)
1258 if result is not None:
1259 return result
1260
1261 # Parse it
1262 if sys_version[:10] == 'IronPython':
1263 # IronPython
1264 name = 'IronPython'
1265 match = _ironpython_sys_version_parser.match(sys_version)
1266 if match is None:
1267 raise ValueError(
1268 'failed to parse IronPython sys.version: %s' %
1269 repr(sys_version))
1270 version, alt_version, compiler = match.groups()
1271 branch = ''
1272 revision = ''
1273 buildno = ''
1274 builddate = ''
1275
1276 elif sys.platform[:4] == 'java':
1277 # Jython
1278 name = 'Jython'
1279 match = _jython_sys_version_parser.match(sys_version)
1280 if match is None:
1281 raise ValueError(
1282 'failed to parse Jython sys.version: %s' %
1283 repr(sys_version))
1284 version, = match.groups()
1285 branch = ''
1286 revision = ''
1287 compiler = sys.platform
1288 buildno = ''
1289 builddate = ''
1290
1291 else:
1292 # CPython
1293 match = _sys_version_parser.match(sys_version)
1294 if match is None:
1295 raise ValueError(
1296 'failed to parse CPython sys.version: %s' %
1297 repr(sys_version))
1298 version, buildno, builddate, buildtime, compiler = \
1299 match.groups()
1300 if hasattr(sys, 'subversion'):
1301 # sys.subversion was added in Python 2.5
1302 name, branch, revision = sys.subversion
1303 else:
1304 name = 'CPython'
1305 branch = ''
1306 revision = ''
1307 builddate = builddate + ' ' + buildtime
1308
1309 # Add the patchlevel version if missing
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001310 l = version.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001311 if len(l) == 2:
1312 l.append('0')
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001313 version = '.'.join(l)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001314
1315 # Build and cache the result
1316 result = (name, version, branch, revision, buildno, builddate, compiler)
1317 _sys_version_cache[sys_version] = result
1318 return result
1319
1320def _test_sys_version():
1321
1322 _sys_version_cache.clear()
1323 for input, output in (
1324 ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
1325 ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
1326 ('IronPython 1.0.60816 on .NET 2.0.50727.42',
1327 ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
1328 ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
1329 ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
1330 ):
1331 parsed = _sys_version(input)
1332 if parsed != output:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001333 print((input, parsed))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001334
1335def python_implementation():
1336
1337 """ Returns a string identifying the Python implementation.
1338
1339 Currently, the following implementations are identified:
1340 'CPython' (C implementation of Python),
1341 'IronPython' (.NET implementation of Python),
1342 'Jython' (Java implementation of Python).
1343
1344 """
1345 return _sys_version()[0]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001346
1347def python_version():
1348
1349 """ Returns the Python version as string 'major.minor.patchlevel'
1350
1351 Note that unlike the Python sys.version, the returned value
1352 will always include the patchlevel (it defaults to 0).
1353
1354 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001355 if hasattr(sys, 'version_info'):
1356 return '%i.%i.%i' % sys.version_info[:3]
1357 return _sys_version()[1]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001358
1359def python_version_tuple():
1360
1361 """ Returns the Python version as tuple (major, minor, patchlevel)
1362 of strings.
1363
1364 Note that unlike the Python sys.version, the returned value
1365 will always include the patchlevel (it defaults to 0).
1366
1367 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001368 if hasattr(sys, 'version_info'):
1369 return sys.version_info[:3]
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001370 return tuple(_sys_version()[1].split('.'))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001371
1372def python_branch():
1373
1374 """ Returns a string identifying the Python implementation
1375 branch.
1376
1377 For CPython this is the Subversion branch from which the
1378 Python binary was built.
1379
1380 If not available, an empty string is returned.
1381
1382 """
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001383
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001384 return _sys_version()[2]
1385
1386def python_revision():
1387
1388 """ Returns a string identifying the Python implementation
1389 revision.
1390
1391 For CPython this is the Subversion revision from which the
1392 Python binary was built.
1393
1394 If not available, an empty string is returned.
1395
1396 """
1397 return _sys_version()[3]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001398
1399def python_build():
1400
1401 """ Returns a tuple (buildno, builddate) stating the Python
1402 build number and date as strings.
1403
1404 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001405 return _sys_version()[4:6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001406
1407def python_compiler():
1408
1409 """ Returns a string identifying the compiler used for compiling
1410 Python.
1411
1412 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001413 return _sys_version()[6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001414
1415### The Opus Magnum of platform strings :-)
1416
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001417_platform_cache = {}
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001418
1419def platform(aliased=0, terse=0):
1420
1421 """ Returns a single string identifying the underlying platform
1422 with as much useful information as possible (but no more :).
Tim Peters0eadaac2003-04-24 16:02:54 +00001423
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001424 The output is intended to be human readable rather than
1425 machine parseable. It may look different on different
1426 platforms and this is intended.
1427
1428 If "aliased" is true, the function will use aliases for
1429 various platforms that report system names which differ from
1430 their common names, e.g. SunOS will be reported as
1431 Solaris. The system_alias() function is used to implement
1432 this.
1433
1434 Setting terse to true causes the function to return only the
1435 absolute minimum information needed to identify the platform.
1436
1437 """
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001438 result = _platform_cache.get((aliased, terse), None)
1439 if result is not None:
1440 return result
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001441
1442 # Get uname information and then apply platform specific cosmetics
1443 # to it...
1444 system,node,release,version,machine,processor = uname()
1445 if machine == processor:
1446 processor = ''
1447 if aliased:
1448 system,release,version = system_alias(system,release,version)
1449
1450 if system == 'Windows':
1451 # MS platforms
1452 rel,vers,csd,ptype = win32_ver(version)
1453 if terse:
1454 platform = _platform(system,release)
1455 else:
1456 platform = _platform(system,release,version,csd)
1457
1458 elif system in ('Linux',):
1459 # Linux based systems
1460 distname,distversion,distid = dist('')
1461 if distname and not terse:
1462 platform = _platform(system,release,machine,processor,
1463 'with',
1464 distname,distversion,distid)
1465 else:
1466 # If the distribution name is unknown check for libc vs. glibc
1467 libcname,libcversion = libc_ver(sys.executable)
1468 platform = _platform(system,release,machine,processor,
1469 'with',
1470 libcname+libcversion)
1471 elif system == 'Java':
1472 # Java platforms
1473 r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001474 if terse or not os_name:
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001475 platform = _platform(system,release,version)
1476 else:
1477 platform = _platform(system,release,version,
1478 'on',
1479 os_name,os_version,os_arch)
1480
1481 elif system == 'MacOS':
1482 # MacOS platforms
1483 if terse:
1484 platform = _platform(system,release)
1485 else:
1486 platform = _platform(system,release,machine)
1487
1488 else:
1489 # Generic handler
1490 if terse:
1491 platform = _platform(system,release)
1492 else:
1493 bits,linkage = architecture(sys.executable)
1494 platform = _platform(system,release,machine,processor,bits,linkage)
Tim Peters0eadaac2003-04-24 16:02:54 +00001495
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001496 _platform_cache[(aliased, terse)] = platform
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001497 return platform
1498
1499### Command line interface
1500
1501if __name__ == '__main__':
1502 # Default is to print the aliased verbose platform string
Tim Peters0eadaac2003-04-24 16:02:54 +00001503 terse = ('terse' in sys.argv or '--terse' in sys.argv)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001504 aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001505 print(platform(aliased,terse))
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001506 sys.exit(0)