blob: 2f0196989109cefcd63786f8890e683adebc51e7 [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),
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +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#
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +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
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +000094 Copyright (c) 2000-2008, 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
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000113__version__ = '1.0.6'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000114
115import sys,string,os,re
116
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 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +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')
148 binary = f.read(chunksize)
149 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:
153 binary = f.read(chunksize)
154 if not binary:
155 break
156 pos = 0
157 continue
158 libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
159 if libcinit and not lib:
160 lib = 'libc'
161 elif glibc:
162 if lib != 'glibc':
163 lib = 'glibc'
164 version = glibcversion
165 elif glibcversion > version:
166 version = glibcversion
167 elif so:
168 if lib != 'glibc':
169 lib = 'libc'
170 if soversion > version:
171 version = soversion
172 if threads and version[-len(threads):] != threads:
173 version = version + threads
174 pos = m.end()
175 f.close()
176 return lib,version
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:
192 tv = string.split(line)
193 if len(tv) == 2:
194 tag,value = tv
195 else:
196 continue
197 if tag == 'MIN_DIST_VERSION':
198 version = string.strip(value)
199 elif tag == 'DIST_IDENT':
200 values = string.split(value,'-')
201 id = values[2]
202 return distname,version,id
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:
208 pkg = string.split(line,'-')
209 if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
210 # XXX does Caldera support non Intel platforms ? If yes,
211 # where can we find the needed id ?
212 return 'OpenLinux',pkg[1],id
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)')
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +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
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000238# See also http://www.novell.com/coolsolutions/feature/11251.html
Tim Petersf733abb2007-01-30 03:03:46 +0000239# and http://linuxmafia.com/faq/Admin/release-files.html
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +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
Marc-André Lemburg50967bd2008-03-08 10:01:43 +0000243_supported_dists = (
244 'SuSE', 'debian', 'fedora', 'redhat', 'centos',
245 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
246 'UnitedLinux', 'turbolinux')
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000247
248def _parse_release_file(firstline):
Tim Petersf733abb2007-01-30 03:03:46 +0000249
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000250 # Parse the first line
251 m = _lsb_release_version.match(firstline)
252 if m is not None:
253 # LSB format: "distro release x.x (codename)"
254 return tuple(m.groups())
255
256 # Pre-LSB format: "distro x.x (codename)"
257 m = _release_version.match(firstline)
258 if m is not None:
259 return tuple(m.groups())
260
261 # Unkown format... take the first two words
262 l = string.split(string.strip(firstline))
263 if l:
264 version = l[0]
265 if len(l) > 1:
266 id = l[1]
267 else:
268 id = ''
269 return '', version, id
270
271def _test_parse_release_file():
Tim Petersf733abb2007-01-30 03:03:46 +0000272
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000273 for input, output in (
274 # Examples of release file contents:
275 ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))
276 ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))
277 ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))
278 ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))
279 ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))
280 ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))
281 ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))
282 ('CentOS release 4', ('CentOS', '4', None))
283 ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia'))
284 ):
285 parsed = _parse_release_file(input)
286 if parsed != output:
287 print (input, parsed)
288
289def linux_distribution(distname='', version='', id='',
290
291 supported_dists=_supported_dists,
292 full_distribution_name=1):
293
294 """ Tries to determine the name of the Linux OS distribution name.
295
296 The function first looks for a distribution release file in
297 /etc and then reverts to _dist_try_harder() in case no
298 suitable files are found.
299
300 supported_dists may be given to define the set of Linux
301 distributions to look for. It defaults to a list of currently
302 supported Linux distributions identified by their release file
303 name.
304
305 If full_distribution_name is true (default), the full
306 distribution read from the OS is returned. Otherwise the short
307 name taken from supported_dists is used.
308
309 Returns a tuple (distname,version,id) which default to the
310 args given as parameters.
311
312 """
313 try:
314 etc = os.listdir('/etc')
315 except os.error:
316 # Probably not a Unix system
317 return distname,version,id
318 etc.sort()
319 for file in etc:
320 m = _release_filename.match(file)
321 if m is not None:
322 _distname,dummy = m.groups()
323 if _distname in supported_dists:
324 distname = _distname
325 break
326 else:
327 return _dist_try_harder(distname,version,id)
Tim Petersf733abb2007-01-30 03:03:46 +0000328
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000329 # Read the first line
330 f = open('/etc/'+file, 'r')
331 firstline = f.readline()
332 f.close()
333 _distname, _version, _id = _parse_release_file(firstline)
334
335 if _distname and full_distribution_name:
336 distname = _distname
337 if _version:
338 version = _version
339 if _id:
340 id = _id
341 return distname, version, id
342
343# To maintain backwards compatibility:
Tim Petersf733abb2007-01-30 03:03:46 +0000344
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000345def dist(distname='',version='',id='',
346
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000347 supported_dists=_supported_dists):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000348
Brett Cannon8ab27df2003-08-05 03:52:04 +0000349 """ Tries to determine the name of the Linux OS distribution name.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000350
351 The function first looks for a distribution release file in
352 /etc and then reverts to _dist_try_harder() in case no
353 suitable files are found.
354
Brett Cannon8ab27df2003-08-05 03:52:04 +0000355 Returns a tuple (distname,version,id) which default to the
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000356 args given as parameters.
357
358 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000359 return linux_distribution(distname, version, id,
360 supported_dists=supported_dists,
361 full_distribution_name=0)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000362
363class _popen:
364
365 """ Fairly portable (alternative) popen implementation.
366
367 This is mostly needed in case os.popen() is not available, or
368 doesn't work as advertised, e.g. in Win9X GUI programs like
369 PythonWin or IDLE.
370
371 Writing to the pipe is currently not supported.
372
373 """
374 tmpfile = ''
375 pipe = None
376 bufsize = None
377 mode = 'r'
378
379 def __init__(self,cmd,mode='r',bufsize=None):
380
381 if mode != 'r':
382 raise ValueError,'popen()-emulation only supports read mode'
383 import tempfile
384 self.tmpfile = tmpfile = tempfile.mktemp()
385 os.system(cmd + ' > %s' % tmpfile)
386 self.pipe = open(tmpfile,'rb')
387 self.bufsize = bufsize
388 self.mode = mode
389
390 def read(self):
391
392 return self.pipe.read()
393
394 def readlines(self):
395
396 if self.bufsize is not None:
397 return self.pipe.readlines()
398
399 def close(self,
400
401 remove=os.unlink,error=os.error):
402
403 if self.pipe:
404 rc = self.pipe.close()
405 else:
406 rc = 255
407 if self.tmpfile:
408 try:
409 remove(self.tmpfile)
410 except error:
411 pass
412 return rc
413
414 # Alias
415 __del__ = close
416
417def popen(cmd, mode='r', bufsize=None):
418
419 """ Portable popen() interface.
420 """
421 # Find a working popen implementation preferring win32pipe.popen
422 # over os.popen over _popen
423 popen = None
424 if os.environ.get('OS','') == 'Windows_NT':
425 # On NT win32pipe should work; on Win9x it hangs due to bugs
426 # in the MS C lib (see MS KnowledgeBase article Q150956)
427 try:
428 import win32pipe
429 except ImportError:
430 pass
431 else:
432 popen = win32pipe.popen
433 if popen is None:
434 if hasattr(os,'popen'):
435 popen = os.popen
436 # Check whether it works... it doesn't in GUI programs
437 # on Windows platforms
438 if sys.platform == 'win32': # XXX Others too ?
439 try:
440 popen('')
441 except os.error:
442 popen = _popen
443 else:
444 popen = _popen
445 if bufsize is None:
446 return popen(cmd,mode)
447 else:
448 return popen(cmd,mode,bufsize)
449
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000450def _norm_version(version, build=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000451
Brett Cannon8ab27df2003-08-05 03:52:04 +0000452 """ Normalize the version and build strings and return a single
Walter Dörwalde5a7fad2005-11-21 17:01:27 +0000453 version string using the format major.minor.build (or patchlevel).
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000454 """
455 l = string.split(version,'.')
456 if build:
457 l.append(build)
458 try:
459 ints = map(int,l)
460 except ValueError:
461 strings = l
462 else:
463 strings = map(str,ints)
464 version = string.join(strings[:3],'.')
465 return version
466
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000467_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
468 '.*'
469 'Version ([\d.]+))')
470
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000471def _syscmd_ver(system='', release='', version='',
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000472
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000473 supported_platforms=('win32','win16','dos','os2')):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000474
475 """ Tries to figure out the OS version used and returns
476 a tuple (system,release,version).
Tim Peters0eadaac2003-04-24 16:02:54 +0000477
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000478 It uses the "ver" shell command for this which is known
479 to exists on Windows, DOS and OS/2. XXX Others too ?
480
481 In case this fails, the given parameters are used as
482 defaults.
483
484 """
485 if sys.platform not in supported_platforms:
486 return system,release,version
487
488 # Try some common cmd strings
489 for cmd in ('ver','command /c ver','cmd /c ver'):
490 try:
491 pipe = popen(cmd)
492 info = pipe.read()
493 if pipe.close():
494 raise os.error,'command failed'
495 # XXX How can I supress shell errors from being written
496 # to stderr ?
497 except os.error,why:
498 #print 'Command %s failed: %s' % (cmd,why)
499 continue
500 except IOError,why:
501 #print 'Command %s failed: %s' % (cmd,why)
502 continue
503 else:
504 break
505 else:
506 return system,release,version
507
508 # Parse the output
509 info = string.strip(info)
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000510 m = _ver_output.match(info)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000511 if m is not None:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000512 system,release,version = m.groups()
513 # Strip trailing dots from version and release
514 if release[-1] == '.':
515 release = release[:-1]
516 if version[-1] == '.':
517 version = version[:-1]
518 # Normalize the version and build strings (eliminating additional
519 # zeros)
520 version = _norm_version(version)
521 return system,release,version
522
523def _win32_getvalue(key,name,default=''):
524
525 """ Read a value for name from the registry key.
526
527 In case this fails, default is returned.
528
529 """
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000530 try:
531 # Use win32api if available
532 from win32api import RegQueryValueEx
533 except ImportError:
534 # On Python 2.0 and later, emulate using _winreg
535 import _winreg
536 RegQueryValueEx = _winreg.QueryValueEx
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000537 try:
538 return RegQueryValueEx(key,name)
539 except:
540 return default
541
542def win32_ver(release='',version='',csd='',ptype=''):
543
544 """ Get additional version information from the Windows Registry
545 and return a tuple (version,csd,ptype) referring to version
546 number, CSD level and OS type (multi/single
547 processor).
548
549 As a hint: ptype returns 'Uniprocessor Free' on single
550 processor NT machines and 'Multiprocessor Free' on multi
551 processor machines. The 'Free' refers to the OS version being
552 free of debugging code. It could also state 'Checked' which
553 means the OS version uses debugging code, i.e. code that
554 checks arguments, ranges, etc. (Thomas Heller).
555
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000556 Note: this function works best with Mark Hammond's win32
557 package installed, but also on Python 2.3 and later. It
558 obviously only runs on Win32 compatible platforms.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000559
560 """
561 # XXX Is there any way to find out the processor type on WinXX ?
562 # XXX Is win32 available on Windows CE ?
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000563 #
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000564 # Adapted from code posted by Karl Putland to comp.lang.python.
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000565 #
566 # The mappings between reg. values and release names can be found
567 # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000568
569 # Import the needed APIs
570 try:
571 import win32api
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000572 from win32api import RegQueryValueEx, RegOpenKeyEx, \
573 RegCloseKey, GetVersionEx
574 from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
575 VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000576 except ImportError:
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000577 # Emulate the win32api module using Python APIs
578 try:
579 sys.getwindowsversion
580 except AttributeError:
581 # No emulation possible, so return the defaults...
582 return release,version,csd,ptype
583 else:
584 # Emulation using _winreg (added in Python 2.0) and
585 # sys.getwindowsversion() (added in Python 2.3)
586 import _winreg
587 GetVersionEx = sys.getwindowsversion
588 RegQueryValueEx = _winreg.QueryValueEx
589 RegOpenKeyEx = _winreg.OpenKeyEx
590 RegCloseKey = _winreg.CloseKey
591 HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
592 VER_PLATFORM_WIN32_WINDOWS = 1
593 VER_PLATFORM_WIN32_NT = 2
594 VER_NT_WORKSTATION = 1
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000595
596 # Find out the registry key and some general version infos
597 maj,min,buildno,plat,csd = GetVersionEx()
598 version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
599 if csd[:13] == 'Service Pack ':
600 csd = 'SP' + csd[13:]
601 if plat == VER_PLATFORM_WIN32_WINDOWS:
602 regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
603 # Try to guess the release name
604 if maj == 4:
605 if min == 0:
606 release = '95'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000607 elif min == 10:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000608 release = '98'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000609 elif min == 90:
610 release = 'Me'
611 else:
612 release = 'postMe'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000613 elif maj == 5:
614 release = '2000'
615 elif plat == VER_PLATFORM_WIN32_NT:
616 regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
617 if maj <= 4:
618 release = 'NT'
619 elif maj == 5:
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000620 if min == 0:
621 release = '2000'
622 elif min == 1:
623 release = 'XP'
624 elif min == 2:
625 release = '2003Server'
626 else:
627 release = 'post2003'
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +0000628 elif maj == 6:
629 if min == 0:
630 # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000631 try:
632 productType = GetVersionEx(1)[8]
633 except TypeError:
634 # sys.getwindowsversion() doesn't take any arguments, so
635 # we cannot detect 2008 Server that way.
636 # XXX Add some other means of detecting 2008 Server ?!
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +0000637 release = 'Vista'
638 else:
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000639 if productType == VER_NT_WORKSTATION:
640 release = 'Vista'
641 else:
642 release = '2008Server'
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +0000643 else:
644 release = 'post2008Server'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000645 else:
646 if not release:
647 # E.g. Win3.1 with win32s
648 release = '%i.%i' % (maj,min)
649 return release,version,csd,ptype
650
651 # Open the registry key
652 try:
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000653 keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000654 # Get a value to make sure the key exists...
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000655 RegQueryValueEx(keyCurVer, 'SystemRoot')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000656 except:
657 return release,version,csd,ptype
Tim Peters0eadaac2003-04-24 16:02:54 +0000658
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000659 # Parse values
660 #subversion = _win32_getvalue(keyCurVer,
661 # 'SubVersionNumber',
662 # ('',1))[0]
663 #if subversion:
664 # release = release + subversion # 95a, 95b, etc.
665 build = _win32_getvalue(keyCurVer,
666 'CurrentBuildNumber',
667 ('',1))[0]
668 ptype = _win32_getvalue(keyCurVer,
669 'CurrentType',
670 (ptype,1))[0]
671
672 # Normalize version
673 version = _norm_version(version,build)
674
675 # Close key
676 RegCloseKey(keyCurVer)
677 return release,version,csd,ptype
678
679def _mac_ver_lookup(selectors,default=None):
680
681 from gestalt import gestalt
Jack Jansena290e3d2003-08-11 11:08:49 +0000682 import MacOS
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000683 l = []
684 append = l.append
685 for selector in selectors:
686 try:
687 append(gestalt(selector))
Jack Jansena290e3d2003-08-11 11:08:49 +0000688 except (RuntimeError, MacOS.Error):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000689 append(default)
690 return l
691
692def _bcd2str(bcd):
693
694 return hex(bcd)[2:]
695
696def mac_ver(release='',versioninfo=('','',''),machine=''):
697
698 """ Get MacOS version information and return it as tuple (release,
699 versioninfo, machine) with versioninfo being a tuple (version,
700 dev_stage, non_release_version).
701
Brett Cannon8ab27df2003-08-05 03:52:04 +0000702 Entries which cannot be determined are set to the paramter values
703 which default to ''. All tuple entries are strings.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000704
705 Thanks to Mark R. Levinson for mailing documentation links and
706 code examples for this function. Documentation for the
707 gestalt() API is available online at:
708
709 http://www.rgaros.nl/gestalt/
710
711 """
712 # Check whether the version info module is available
713 try:
714 import gestalt
Jack Jansena290e3d2003-08-11 11:08:49 +0000715 import MacOS
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000716 except ImportError:
717 return release,versioninfo,machine
718 # Get the infos
719 sysv,sysu,sysa = _mac_ver_lookup(('sysv','sysu','sysa'))
720 # Decode the infos
721 if sysv:
722 major = (sysv & 0xFF00) >> 8
723 minor = (sysv & 0x00F0) >> 4
724 patch = (sysv & 0x000F)
725 release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
726 if sysu:
727 major = int((sysu & 0xFF000000L) >> 24)
728 minor = (sysu & 0x00F00000) >> 20
729 bugfix = (sysu & 0x000F0000) >> 16
730 stage = (sysu & 0x0000FF00) >> 8
731 nonrel = (sysu & 0x000000FF)
732 version = '%s.%i.%i' % (_bcd2str(major),minor,bugfix)
733 nonrel = _bcd2str(nonrel)
734 stage = {0x20:'development',
735 0x40:'alpha',
736 0x60:'beta',
737 0x80:'final'}.get(stage,'')
738 versioninfo = (version,stage,nonrel)
739 if sysa:
Tim Peters0eadaac2003-04-24 16:02:54 +0000740 machine = {0x1: '68k',
Ronald Oussoren749d0702006-04-17 13:37:15 +0000741 0x2: 'PowerPC',
742 0xa: 'i386'}.get(sysa,'')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000743 return release,versioninfo,machine
744
Neal Norwitz9b924c62003-06-29 04:17:45 +0000745def _java_getprop(name,default):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000746
747 from java.lang import System
748 try:
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000749 value = System.getProperty(name)
750 if value is None:
751 return default
752 return value
753 except AttributeError:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000754 return default
755
756def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
Tim Peters0eadaac2003-04-24 16:02:54 +0000757
Brett Cannon8ab27df2003-08-05 03:52:04 +0000758 """ Version interface for Jython.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000759
760 Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
761 a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
762 tuple (os_name,os_version,os_arch).
763
764 Values which cannot be determined are set to the defaults
765 given as parameters (which all default to '').
766
767 """
768 # Import the needed APIs
769 try:
770 import java.lang
771 except ImportError:
772 return release,vendor,vminfo,osinfo
773
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000774 vendor = _java_getprop('java.vendor', vendor)
775 release = _java_getprop('java.version', release)
776 vm_name, vm_release, vm_vendor = vminfo
777 vm_name = _java_getprop('java.vm.name', vm_name)
778 vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
779 vm_release = _java_getprop('java.vm.version', vm_release)
780 vminfo = vm_name, vm_release, vm_vendor
781 os_name, os_version, os_arch = osinfo
782 os_arch = _java_getprop('java.os.arch', os_arch)
783 os_name = _java_getprop('java.os.name', os_name)
784 os_version = _java_getprop('java.os.version', os_version)
785 osinfo = os_name, os_version, os_arch
Tim Peters0eadaac2003-04-24 16:02:54 +0000786
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000787 return release, vendor, vminfo, osinfo
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000788
789### System name aliasing
790
791def system_alias(system,release,version):
792
793 """ Returns (system,release,version) aliased to common
794 marketing names used for some systems.
795
796 It also does some reordering of the information in some cases
797 where it would otherwise cause confusion.
798
799 """
800 if system == 'Rhapsody':
801 # Apple's BSD derivative
802 # XXX How can we determine the marketing release number ?
803 return 'MacOS X Server',system+release,version
804
805 elif system == 'SunOS':
806 # Sun's OS
807 if release < '5':
808 # These releases use the old name SunOS
809 return system,release,version
810 # Modify release (marketing release = SunOS release - 3)
811 l = string.split(release,'.')
812 if l:
813 try:
814 major = int(l[0])
815 except ValueError:
816 pass
817 else:
818 major = major - 3
819 l[0] = str(major)
820 release = string.join(l,'.')
821 if release < '6':
822 system = 'Solaris'
823 else:
824 # XXX Whatever the new SunOS marketing name is...
825 system = 'Solaris'
826
827 elif system == 'IRIX64':
828 # IRIX reports IRIX64 on platforms with 64-bit support; yet it
829 # is really a version and not a different platform, since 32-bit
830 # apps are also supported..
831 system = 'IRIX'
832 if version:
833 version = version + ' (64bit)'
834 else:
835 version = '64bit'
836
837 elif system in ('win32','win16'):
838 # In case one of the other tricks
839 system = 'Windows'
840
841 return system,release,version
842
843### Various internal helpers
844
845def _platform(*args):
846
847 """ Helper to format the platform string in a filename
848 compatible format e.g. "system-version-machine".
849 """
850 # Format the platform string
851 platform = string.join(
852 map(string.strip,
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000853 filter(len, args)),
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000854 '-')
855
856 # Cleanup some possible filename obstacles...
857 replace = string.replace
858 platform = replace(platform,' ','_')
859 platform = replace(platform,'/','-')
860 platform = replace(platform,'\\','-')
861 platform = replace(platform,':','-')
862 platform = replace(platform,';','-')
863 platform = replace(platform,'"','-')
864 platform = replace(platform,'(','-')
865 platform = replace(platform,')','-')
866
867 # No need to report 'unknown' information...
868 platform = replace(platform,'unknown','')
869
870 # Fold '--'s and remove trailing '-'
871 while 1:
872 cleaned = replace(platform,'--','-')
873 if cleaned == platform:
874 break
875 platform = cleaned
876 while platform[-1] == '-':
877 platform = platform[:-1]
878
879 return platform
880
881def _node(default=''):
882
883 """ Helper to determine the node name of this machine.
884 """
885 try:
886 import socket
887 except ImportError:
888 # No sockets...
889 return default
890 try:
891 return socket.gethostname()
892 except socket.error:
893 # Still not working...
894 return default
895
896# os.path.abspath is new in Python 1.5.2:
897if not hasattr(os.path,'abspath'):
898
899 def _abspath(path,
900
901 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
902 normpath=os.path.normpath):
903
904 if not isabs(path):
905 path = join(getcwd(), path)
906 return normpath(path)
907
908else:
909
910 _abspath = os.path.abspath
911
912def _follow_symlinks(filepath):
913
914 """ In case filepath is a symlink, follow it until a
915 real file is reached.
916 """
917 filepath = _abspath(filepath)
918 while os.path.islink(filepath):
919 filepath = os.path.normpath(
920 os.path.join(filepath,os.readlink(filepath)))
921 return filepath
922
923def _syscmd_uname(option,default=''):
924
925 """ Interface to the system's uname command.
926 """
927 if sys.platform in ('dos','win32','win16','os2'):
928 # XXX Others too ?
929 return default
930 try:
931 f = os.popen('uname %s 2> /dev/null' % option)
932 except (AttributeError,os.error):
933 return default
934 output = string.strip(f.read())
935 rc = f.close()
936 if not output or rc:
937 return default
938 else:
939 return output
940
941def _syscmd_file(target,default=''):
942
943 """ Interface to the system's file command.
944
945 The function uses the -b option of the file command to have it
946 ommit the filename in its output and if possible the -L option
947 to have the command follow symlinks. It returns default in
948 case the command should fail.
949
950 """
951 target = _follow_symlinks(target)
952 try:
953 f = os.popen('file %s 2> /dev/null' % target)
954 except (AttributeError,os.error):
955 return default
956 output = string.strip(f.read())
957 rc = f.close()
958 if not output or rc:
959 return default
960 else:
961 return output
962
963### Information about the used architecture
964
965# Default values for architecture; non-empty strings override the
966# defaults given as parameters
967_default_architecture = {
968 'win32': ('','WindowsPE'),
969 'win16': ('','Windows'),
970 'dos': ('','MSDOS'),
971}
972
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000973_architecture_split = re.compile(r'[\s,]').split
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000974
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000975def architecture(executable=sys.executable,bits='',linkage=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000976
977 """ Queries the given executable (defaults to the Python interpreter
Brett Cannon8ab27df2003-08-05 03:52:04 +0000978 binary) for various architecture information.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000979
Brett Cannon8ab27df2003-08-05 03:52:04 +0000980 Returns a tuple (bits,linkage) which contains information about
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000981 the bit architecture and the linkage format used for the
982 executable. Both values are returned as strings.
983
984 Values that cannot be determined are returned as given by the
985 parameter presets. If bits is given as '', the sizeof(pointer)
986 (or sizeof(long) on Python version < 1.5.2) is used as
987 indicator for the supported pointer size.
988
989 The function relies on the system's "file" command to do the
990 actual work. This is available on most if not all Unix
Brett Cannon8ab27df2003-08-05 03:52:04 +0000991 platforms. On some non-Unix platforms where the "file" command
992 does not exist and the executable is set to the Python interpreter
993 binary defaults from _default_architecture are used.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000994
995 """
996 # Use the sizeof(pointer) as default number of bits if nothing
997 # else is given as default.
998 if not bits:
999 import struct
1000 try:
1001 size = struct.calcsize('P')
1002 except struct.error:
1003 # Older installations can only query longs
1004 size = struct.calcsize('l')
1005 bits = str(size*8) + 'bit'
Tim Peters0eadaac2003-04-24 16:02:54 +00001006
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001007 # Get data from the 'file' system command
Marc-André Lemburg3b8f60b2007-01-13 23:13:54 +00001008 if executable:
1009 output = _syscmd_file(executable, '')
1010 else:
1011 output = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001012
1013 if not output and \
1014 executable == sys.executable:
1015 # "file" command did not return anything; we'll try to provide
Tim Peters0eadaac2003-04-24 16:02:54 +00001016 # some sensible defaults then...
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001017 if _default_architecture.has_key(sys.platform):
1018 b,l = _default_architecture[sys.platform]
1019 if b:
1020 bits = b
1021 if l:
1022 linkage = l
1023 return bits,linkage
1024
1025 # Split the output into a list of strings omitting the filename
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +00001026 fileout = _architecture_split(output)[1:]
Tim Peters0eadaac2003-04-24 16:02:54 +00001027
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001028 if 'executable' not in fileout:
1029 # Format not supported
1030 return bits,linkage
1031
1032 # Bits
1033 if '32-bit' in fileout:
1034 bits = '32bit'
1035 elif 'N32' in fileout:
1036 # On Irix only
1037 bits = 'n32bit'
1038 elif '64-bit' in fileout:
1039 bits = '64bit'
1040
1041 # Linkage
1042 if 'ELF' in fileout:
1043 linkage = 'ELF'
1044 elif 'PE' in fileout:
1045 # E.g. Windows uses this format
1046 if 'Windows' in fileout:
1047 linkage = 'WindowsPE'
1048 else:
1049 linkage = 'PE'
1050 elif 'COFF' in fileout:
1051 linkage = 'COFF'
1052 elif 'MS-DOS' in fileout:
1053 linkage = 'MSDOS'
1054 else:
1055 # XXX the A.OUT format also falls under this class...
1056 pass
1057
1058 return bits,linkage
1059
1060### Portable uname() interface
Tim Peters0eadaac2003-04-24 16:02:54 +00001061
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001062_uname_cache = None
1063
1064def uname():
1065
1066 """ Fairly portable uname interface. Returns a tuple
1067 of strings (system,node,release,version,machine,processor)
1068 identifying the underlying platform.
1069
1070 Note that unlike the os.uname function this also returns
Brett Cannon8ab27df2003-08-05 03:52:04 +00001071 possible processor information as an additional tuple entry.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001072
1073 Entries which cannot be determined are set to ''.
1074
1075 """
1076 global _uname_cache
1077
1078 if _uname_cache is not None:
1079 return _uname_cache
1080
1081 # Get some infos from the builtin os.uname API...
1082 try:
1083 system,node,release,version,machine = os.uname()
1084
1085 except AttributeError:
1086 # Hmm, no uname... we'll have to poke around the system then.
1087 system = sys.platform
1088 release = ''
1089 version = ''
1090 node = _node()
1091 machine = ''
1092 processor = ''
1093 use_syscmd_ver = 1
1094
1095 # Try win32_ver() on win32 platforms
1096 if system == 'win32':
1097 release,version,csd,ptype = win32_ver()
1098 if release and version:
1099 use_syscmd_ver = 0
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +00001100 # Try to use the PROCESSOR_* environment variables
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001101 # available on Win XP and later; see
1102 # http://support.microsoft.com/kb/888731 and
1103 # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +00001104 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
1105 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
Tim Peters0eadaac2003-04-24 16:02:54 +00001106
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001107 # Try the 'ver' system command available on some
1108 # platforms
1109 if use_syscmd_ver:
1110 system,release,version = _syscmd_ver(system)
Marc-André Lemburgcdc79232004-06-19 17:17:00 +00001111 # Normalize system to what win32_ver() normally returns
1112 # (_syscmd_ver() tends to return the vendor name as well)
1113 if system == 'Microsoft Windows':
1114 system = 'Windows'
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +00001115 elif system == 'Microsoft' and release == 'Windows':
1116 # Under Windows Vista and Windows Server 2008,
1117 # Microsoft changed the output of the ver command. The
1118 # release is no longer printed. This causes the
1119 # system and release to be misidentified.
1120 system = 'Windows'
1121 if '6.0' == version[:3]:
1122 release = 'Vista'
1123 else:
1124 release = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001125
1126 # In case we still don't know anything useful, we'll try to
1127 # help ourselves
1128 if system in ('win32','win16'):
1129 if not version:
1130 if system == 'win32':
1131 version = '32bit'
1132 else:
1133 version = '16bit'
1134 system = 'Windows'
1135
1136 elif system[:4] == 'java':
1137 release,vendor,vminfo,osinfo = java_ver()
1138 system = 'Java'
1139 version = string.join(vminfo,', ')
1140 if not version:
1141 version = vendor
1142
1143 elif os.name == 'mac':
1144 release,(version,stage,nonrel),machine = mac_ver()
1145 system = 'MacOS'
1146
1147 else:
1148 # System specific extensions
1149 if system == 'OpenVMS':
1150 # OpenVMS seems to have release and version mixed up
1151 if not release or release == '0':
1152 release = version
1153 version = ''
1154 # Get processor information
1155 try:
1156 import vms_lib
1157 except ImportError:
1158 pass
1159 else:
1160 csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
1161 if (cpu_number >= 128):
1162 processor = 'Alpha'
1163 else:
1164 processor = 'VAX'
1165 else:
1166 # Get processor information from the uname system command
1167 processor = _syscmd_uname('-p','')
1168
1169 # 'unknown' is not really any useful as information; we'll convert
1170 # it to '' which is more portable
1171 if system == 'unknown':
1172 system = ''
1173 if node == 'unknown':
1174 node = ''
1175 if release == 'unknown':
1176 release = ''
1177 if version == 'unknown':
1178 version = ''
1179 if machine == 'unknown':
1180 machine = ''
1181 if processor == 'unknown':
1182 processor = ''
Sean Reifscheiderf09597c2007-09-17 20:53:21 +00001183
1184 # normalize name
1185 if system == 'Microsoft' and release == 'Windows':
1186 system = 'Windows'
1187 release = 'Vista'
1188
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001189 _uname_cache = system,node,release,version,machine,processor
1190 return _uname_cache
1191
1192### Direct interfaces to some of the uname() return values
1193
1194def system():
1195
1196 """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
1197
1198 An empty string is returned if the value cannot be determined.
1199
1200 """
1201 return uname()[0]
1202
1203def node():
1204
Brett Cannon8ab27df2003-08-05 03:52:04 +00001205 """ Returns the computer's network name (which may not be fully
1206 qualified)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001207
1208 An empty string is returned if the value cannot be determined.
1209
1210 """
1211 return uname()[1]
1212
1213def release():
1214
1215 """ Returns the system's release, e.g. '2.2.0' or 'NT'
1216
1217 An empty string is returned if the value cannot be determined.
1218
1219 """
1220 return uname()[2]
1221
1222def version():
1223
1224 """ Returns the system's release version, e.g. '#3 on degas'
1225
1226 An empty string is returned if the value cannot be determined.
1227
1228 """
1229 return uname()[3]
1230
1231def machine():
1232
1233 """ Returns the machine type, e.g. 'i386'
1234
1235 An empty string is returned if the value cannot be determined.
1236
1237 """
1238 return uname()[4]
1239
1240def processor():
1241
1242 """ Returns the (true) processor name, e.g. 'amdk6'
1243
1244 An empty string is returned if the value cannot be
1245 determined. Note that many platforms do not provide this
1246 information or simply return the same value as for machine(),
1247 e.g. NetBSD does this.
1248
1249 """
1250 return uname()[5]
1251
1252### Various APIs for extracting information from sys.version
1253
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001254_sys_version_parser = re.compile(
1255 r'([\w.+]+)\s*'
1256 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
1257 '\[([^\]]+)\]?')
1258
1259_jython_sys_version_parser = re.compile(
1260 r'([\d\.]+)')
1261
1262_ironpython_sys_version_parser = re.compile(
1263 r'IronPython\s*'
1264 '([\d\.]+)'
1265 '(?: \(([\d\.]+)\))?'
1266 ' on (.NET [\d\.]+)')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001267
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001268_sys_version_cache = {}
1269
1270def _sys_version(sys_version=None):
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001271
1272 """ Returns a parsed version of Python's sys.version as tuple
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001273 (name, version, branch, revision, buildno, builddate, compiler)
1274 referring to the Python implementation name, version, branch,
1275 revision, build number, build date/time as string and the compiler
1276 identification string.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001277
1278 Note that unlike the Python sys.version, the returned value
1279 for the Python version will always include the patchlevel (it
1280 defaults to '.0').
1281
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001282 The function returns empty strings for tuple entries that
1283 cannot be determined.
1284
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001285 sys_version may be given to parse an alternative version
1286 string, e.g. if the version was read from a different Python
1287 interpreter.
1288
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001289 """
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001290 # Get the Python version
1291 if sys_version is None:
1292 sys_version = sys.version
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001293
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001294 # Try the cache first
1295 result = _sys_version_cache.get(sys_version, None)
1296 if result is not None:
1297 return result
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001298
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001299 # Parse it
1300 if sys_version[:10] == 'IronPython':
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001301 # IronPython
1302 name = 'IronPython'
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001303 match = _ironpython_sys_version_parser.match(sys_version)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001304 if match is None:
1305 raise ValueError(
1306 'failed to parse IronPython sys.version: %s' %
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001307 repr(sys_version))
1308 version, alt_version, compiler = match.groups()
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001309 branch = ''
1310 revision = ''
1311 buildno = ''
1312 builddate = ''
1313
1314 elif sys.platform[:4] == 'java':
1315 # Jython
1316 name = 'Jython'
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001317 match = _jython_sys_version_parser.match(sys_version)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001318 if match is None:
1319 raise ValueError(
1320 'failed to parse Jython sys.version: %s' %
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001321 repr(sys_version))
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001322 version, = match.groups()
1323 branch = ''
1324 revision = ''
1325 compiler = sys.platform
1326 buildno = ''
1327 builddate = ''
1328
1329 else:
1330 # CPython
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001331 match = _sys_version_parser.match(sys_version)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001332 if match is None:
1333 raise ValueError(
1334 'failed to parse CPython sys.version: %s' %
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001335 repr(sys_version))
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001336 version, buildno, builddate, buildtime, compiler = \
1337 match.groups()
1338 if hasattr(sys, 'subversion'):
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001339 # sys.subversion was added in Python 2.5
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001340 name, branch, revision = sys.subversion
1341 else:
1342 name = 'CPython'
1343 branch = ''
1344 revision = ''
1345 builddate = builddate + ' ' + buildtime
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001346
1347 # Add the patchlevel version if missing
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001348 l = string.split(version, '.')
1349 if len(l) == 2:
1350 l.append('0')
1351 version = string.join(l, '.')
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001352
1353 # Build and cache the result
1354 result = (name, version, branch, revision, buildno, builddate, compiler)
1355 _sys_version_cache[sys_version] = result
1356 return result
1357
1358def _test_sys_version():
1359
1360 _sys_version_cache.clear()
1361 for input, output in (
1362 ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
1363 ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
1364 ('IronPython 1.0.60816 on .NET 2.0.50727.42',
1365 ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
1366 ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
1367 ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
1368 ):
1369 parsed = _sys_version(input)
1370 if parsed != output:
1371 print (input, parsed)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001372
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001373def python_implementation():
1374
1375 """ Returns a string identifying the Python implementation.
1376
1377 Currently, the following implementations are identified:
1378 'CPython' (C implementation of Python),
1379 'IronPython' (.NET implementation of Python),
1380 'Jython' (Java implementation of Python).
1381
1382 """
1383 return _sys_version()[0]
1384
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001385def python_version():
1386
1387 """ Returns the Python version as string 'major.minor.patchlevel'
1388
1389 Note that unlike the Python sys.version, the returned value
1390 will always include the patchlevel (it defaults to 0).
1391
1392 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001393 if hasattr(sys, 'version_info'):
1394 return '%i.%i.%i' % sys.version_info[:3]
1395 return _sys_version()[1]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001396
1397def python_version_tuple():
1398
1399 """ Returns the Python version as tuple (major, minor, patchlevel)
1400 of strings.
1401
1402 Note that unlike the Python sys.version, the returned value
1403 will always include the patchlevel (it defaults to 0).
1404
1405 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001406 if hasattr(sys, 'version_info'):
1407 return sys.version_info[:3]
1408 return tuple(string.split(_sys_version()[1], '.'))
1409
1410def python_branch():
1411
Neal Norwitz4b86f8b2007-01-13 21:22:37 +00001412 """ Returns a string identifying the Python implementation
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001413 branch.
1414
1415 For CPython this is the Subversion branch from which the
1416 Python binary was built.
1417
1418 If not available, an empty string is returned.
1419
1420 """
Tim Petersf733abb2007-01-30 03:03:46 +00001421
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001422 return _sys_version()[2]
1423
1424def python_revision():
1425
Neal Norwitz4b86f8b2007-01-13 21:22:37 +00001426 """ Returns a string identifying the Python implementation
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001427 revision.
1428
1429 For CPython this is the Subversion revision from which the
1430 Python binary was built.
1431
1432 If not available, an empty string is returned.
1433
1434 """
1435 return _sys_version()[3]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001436
1437def python_build():
1438
1439 """ Returns a tuple (buildno, builddate) stating the Python
1440 build number and date as strings.
1441
1442 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001443 return _sys_version()[4:6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001444
1445def python_compiler():
1446
1447 """ Returns a string identifying the compiler used for compiling
1448 Python.
1449
1450 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001451 return _sys_version()[6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001452
1453### The Opus Magnum of platform strings :-)
1454
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001455_platform_cache = {}
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001456
1457def platform(aliased=0, terse=0):
1458
1459 """ Returns a single string identifying the underlying platform
1460 with as much useful information as possible (but no more :).
Tim Peters0eadaac2003-04-24 16:02:54 +00001461
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001462 The output is intended to be human readable rather than
1463 machine parseable. It may look different on different
1464 platforms and this is intended.
1465
1466 If "aliased" is true, the function will use aliases for
1467 various platforms that report system names which differ from
1468 their common names, e.g. SunOS will be reported as
1469 Solaris. The system_alias() function is used to implement
1470 this.
1471
1472 Setting terse to true causes the function to return only the
1473 absolute minimum information needed to identify the platform.
1474
1475 """
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001476 result = _platform_cache.get((aliased, terse), None)
1477 if result is not None:
1478 return result
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001479
1480 # Get uname information and then apply platform specific cosmetics
1481 # to it...
1482 system,node,release,version,machine,processor = uname()
1483 if machine == processor:
1484 processor = ''
1485 if aliased:
1486 system,release,version = system_alias(system,release,version)
1487
1488 if system == 'Windows':
1489 # MS platforms
1490 rel,vers,csd,ptype = win32_ver(version)
1491 if terse:
1492 platform = _platform(system,release)
1493 else:
1494 platform = _platform(system,release,version,csd)
1495
1496 elif system in ('Linux',):
1497 # Linux based systems
1498 distname,distversion,distid = dist('')
1499 if distname and not terse:
1500 platform = _platform(system,release,machine,processor,
1501 'with',
1502 distname,distversion,distid)
1503 else:
1504 # If the distribution name is unknown check for libc vs. glibc
1505 libcname,libcversion = libc_ver(sys.executable)
1506 platform = _platform(system,release,machine,processor,
1507 'with',
1508 libcname+libcversion)
1509 elif system == 'Java':
1510 # Java platforms
1511 r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001512 if terse or not os_name:
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001513 platform = _platform(system,release,version)
1514 else:
1515 platform = _platform(system,release,version,
1516 'on',
1517 os_name,os_version,os_arch)
1518
1519 elif system == 'MacOS':
1520 # MacOS platforms
1521 if terse:
1522 platform = _platform(system,release)
1523 else:
1524 platform = _platform(system,release,machine)
1525
1526 else:
1527 # Generic handler
1528 if terse:
1529 platform = _platform(system,release)
1530 else:
1531 bits,linkage = architecture(sys.executable)
1532 platform = _platform(system,release,machine,processor,bits,linkage)
Tim Peters0eadaac2003-04-24 16:02:54 +00001533
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001534 _platform_cache[(aliased, terse)] = platform
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001535 return platform
1536
1537### Command line interface
1538
1539if __name__ == '__main__':
1540 # Default is to print the aliased verbose platform string
Tim Peters0eadaac2003-04-24 16:02:54 +00001541 terse = ('terse' in sys.argv or '--terse' in sys.argv)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001542 aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
1543 print platform(aliased,terse)
1544 sys.exit(0)