blob: c501456a2ffe21e21cadc24ecee3b8bbfc58052c [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
Georg Brandlf004d9d2009-10-27 15:39:53 +000013# Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
Marc-André Lemburg246d8472003-04-24 11:36:11 +000014#
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
Georg Brandlb6453a92010-03-21 19:16:28 +000094 Copyright (c) 2000-2010, 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
Benjamin Peterson00b90512010-01-25 03:35:04 +0000250 # Default to empty 'version' and 'id' strings. Both defaults are used
251 # when 'firstline' is empty. 'id' defaults to empty when an id can not
252 # be deduced.
253 version = ''
254 id = ''
255
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000256 # Parse the first line
257 m = _lsb_release_version.match(firstline)
258 if m is not None:
259 # LSB format: "distro release x.x (codename)"
260 return tuple(m.groups())
261
262 # Pre-LSB format: "distro x.x (codename)"
263 m = _release_version.match(firstline)
264 if m is not None:
265 return tuple(m.groups())
266
267 # Unkown format... take the first two words
268 l = string.split(string.strip(firstline))
269 if l:
270 version = l[0]
271 if len(l) > 1:
272 id = l[1]
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000273 return '', version, id
274
275def _test_parse_release_file():
Tim Petersf733abb2007-01-30 03:03:46 +0000276
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000277 for input, output in (
278 # Examples of release file contents:
279 ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))
280 ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))
281 ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))
282 ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))
283 ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))
284 ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))
285 ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))
286 ('CentOS release 4', ('CentOS', '4', None))
287 ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia'))
288 ):
289 parsed = _parse_release_file(input)
290 if parsed != output:
291 print (input, parsed)
292
293def linux_distribution(distname='', version='', id='',
294
295 supported_dists=_supported_dists,
296 full_distribution_name=1):
297
298 """ Tries to determine the name of the Linux OS distribution name.
299
300 The function first looks for a distribution release file in
301 /etc and then reverts to _dist_try_harder() in case no
302 suitable files are found.
303
304 supported_dists may be given to define the set of Linux
305 distributions to look for. It defaults to a list of currently
306 supported Linux distributions identified by their release file
307 name.
308
309 If full_distribution_name is true (default), the full
310 distribution read from the OS is returned. Otherwise the short
311 name taken from supported_dists is used.
312
313 Returns a tuple (distname,version,id) which default to the
314 args given as parameters.
315
316 """
317 try:
318 etc = os.listdir('/etc')
319 except os.error:
320 # Probably not a Unix system
321 return distname,version,id
322 etc.sort()
323 for file in etc:
324 m = _release_filename.match(file)
325 if m is not None:
326 _distname,dummy = m.groups()
327 if _distname in supported_dists:
328 distname = _distname
329 break
330 else:
331 return _dist_try_harder(distname,version,id)
Tim Petersf733abb2007-01-30 03:03:46 +0000332
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000333 # Read the first line
334 f = open('/etc/'+file, 'r')
335 firstline = f.readline()
336 f.close()
337 _distname, _version, _id = _parse_release_file(firstline)
338
339 if _distname and full_distribution_name:
340 distname = _distname
341 if _version:
342 version = _version
343 if _id:
344 id = _id
345 return distname, version, id
346
347# To maintain backwards compatibility:
Tim Petersf733abb2007-01-30 03:03:46 +0000348
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000349def dist(distname='',version='',id='',
350
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000351 supported_dists=_supported_dists):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000352
Brett Cannon8ab27df2003-08-05 03:52:04 +0000353 """ Tries to determine the name of the Linux OS distribution name.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000354
355 The function first looks for a distribution release file in
356 /etc and then reverts to _dist_try_harder() in case no
357 suitable files are found.
358
Brett Cannon8ab27df2003-08-05 03:52:04 +0000359 Returns a tuple (distname,version,id) which default to the
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000360 args given as parameters.
361
362 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000363 return linux_distribution(distname, version, id,
364 supported_dists=supported_dists,
365 full_distribution_name=0)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000366
367class _popen:
368
369 """ Fairly portable (alternative) popen implementation.
370
371 This is mostly needed in case os.popen() is not available, or
372 doesn't work as advertised, e.g. in Win9X GUI programs like
373 PythonWin or IDLE.
374
375 Writing to the pipe is currently not supported.
376
377 """
378 tmpfile = ''
379 pipe = None
380 bufsize = None
381 mode = 'r'
382
383 def __init__(self,cmd,mode='r',bufsize=None):
384
385 if mode != 'r':
386 raise ValueError,'popen()-emulation only supports read mode'
387 import tempfile
388 self.tmpfile = tmpfile = tempfile.mktemp()
389 os.system(cmd + ' > %s' % tmpfile)
390 self.pipe = open(tmpfile,'rb')
391 self.bufsize = bufsize
392 self.mode = mode
393
394 def read(self):
395
396 return self.pipe.read()
397
398 def readlines(self):
399
400 if self.bufsize is not None:
401 return self.pipe.readlines()
402
403 def close(self,
404
405 remove=os.unlink,error=os.error):
406
407 if self.pipe:
408 rc = self.pipe.close()
409 else:
410 rc = 255
411 if self.tmpfile:
412 try:
413 remove(self.tmpfile)
414 except error:
415 pass
416 return rc
417
418 # Alias
419 __del__ = close
420
421def popen(cmd, mode='r', bufsize=None):
422
423 """ Portable popen() interface.
424 """
425 # Find a working popen implementation preferring win32pipe.popen
426 # over os.popen over _popen
427 popen = None
428 if os.environ.get('OS','') == 'Windows_NT':
429 # On NT win32pipe should work; on Win9x it hangs due to bugs
430 # in the MS C lib (see MS KnowledgeBase article Q150956)
431 try:
432 import win32pipe
433 except ImportError:
434 pass
435 else:
436 popen = win32pipe.popen
437 if popen is None:
438 if hasattr(os,'popen'):
439 popen = os.popen
440 # Check whether it works... it doesn't in GUI programs
441 # on Windows platforms
442 if sys.platform == 'win32': # XXX Others too ?
443 try:
444 popen('')
445 except os.error:
446 popen = _popen
447 else:
448 popen = _popen
449 if bufsize is None:
450 return popen(cmd,mode)
451 else:
452 return popen(cmd,mode,bufsize)
453
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000454def _norm_version(version, build=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000455
Brett Cannon8ab27df2003-08-05 03:52:04 +0000456 """ Normalize the version and build strings and return a single
Walter Dörwalde5a7fad2005-11-21 17:01:27 +0000457 version string using the format major.minor.build (or patchlevel).
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000458 """
459 l = string.split(version,'.')
460 if build:
461 l.append(build)
462 try:
463 ints = map(int,l)
464 except ValueError:
465 strings = l
466 else:
467 strings = map(str,ints)
468 version = string.join(strings[:3],'.')
469 return version
470
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000471_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
472 '.*'
473 'Version ([\d.]+))')
474
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000475def _syscmd_ver(system='', release='', version='',
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000476
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000477 supported_platforms=('win32','win16','dos','os2')):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000478
479 """ Tries to figure out the OS version used and returns
480 a tuple (system,release,version).
Tim Peters0eadaac2003-04-24 16:02:54 +0000481
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000482 It uses the "ver" shell command for this which is known
483 to exists on Windows, DOS and OS/2. XXX Others too ?
484
485 In case this fails, the given parameters are used as
486 defaults.
487
488 """
489 if sys.platform not in supported_platforms:
490 return system,release,version
491
492 # Try some common cmd strings
493 for cmd in ('ver','command /c ver','cmd /c ver'):
494 try:
495 pipe = popen(cmd)
496 info = pipe.read()
497 if pipe.close():
498 raise os.error,'command failed'
499 # XXX How can I supress shell errors from being written
500 # to stderr ?
501 except os.error,why:
502 #print 'Command %s failed: %s' % (cmd,why)
503 continue
504 except IOError,why:
505 #print 'Command %s failed: %s' % (cmd,why)
506 continue
507 else:
508 break
509 else:
510 return system,release,version
511
512 # Parse the output
513 info = string.strip(info)
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000514 m = _ver_output.match(info)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000515 if m is not None:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000516 system,release,version = m.groups()
517 # Strip trailing dots from version and release
518 if release[-1] == '.':
519 release = release[:-1]
520 if version[-1] == '.':
521 version = version[:-1]
522 # Normalize the version and build strings (eliminating additional
523 # zeros)
524 version = _norm_version(version)
525 return system,release,version
526
527def _win32_getvalue(key,name,default=''):
528
529 """ Read a value for name from the registry key.
530
531 In case this fails, default is returned.
532
533 """
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000534 try:
535 # Use win32api if available
536 from win32api import RegQueryValueEx
537 except ImportError:
538 # On Python 2.0 and later, emulate using _winreg
539 import _winreg
540 RegQueryValueEx = _winreg.QueryValueEx
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000541 try:
542 return RegQueryValueEx(key,name)
543 except:
544 return default
545
546def win32_ver(release='',version='',csd='',ptype=''):
547
548 """ Get additional version information from the Windows Registry
549 and return a tuple (version,csd,ptype) referring to version
550 number, CSD level and OS type (multi/single
551 processor).
552
553 As a hint: ptype returns 'Uniprocessor Free' on single
554 processor NT machines and 'Multiprocessor Free' on multi
555 processor machines. The 'Free' refers to the OS version being
556 free of debugging code. It could also state 'Checked' which
557 means the OS version uses debugging code, i.e. code that
558 checks arguments, ranges, etc. (Thomas Heller).
559
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000560 Note: this function works best with Mark Hammond's win32
561 package installed, but also on Python 2.3 and later. It
562 obviously only runs on Win32 compatible platforms.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000563
564 """
565 # XXX Is there any way to find out the processor type on WinXX ?
566 # XXX Is win32 available on Windows CE ?
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000567 #
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000568 # Adapted from code posted by Karl Putland to comp.lang.python.
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000569 #
570 # The mappings between reg. values and release names can be found
571 # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000572
573 # Import the needed APIs
574 try:
575 import win32api
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000576 from win32api import RegQueryValueEx, RegOpenKeyEx, \
577 RegCloseKey, GetVersionEx
578 from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
579 VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000580 except ImportError:
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000581 # Emulate the win32api module using Python APIs
582 try:
583 sys.getwindowsversion
584 except AttributeError:
585 # No emulation possible, so return the defaults...
586 return release,version,csd,ptype
587 else:
588 # Emulation using _winreg (added in Python 2.0) and
589 # sys.getwindowsversion() (added in Python 2.3)
590 import _winreg
591 GetVersionEx = sys.getwindowsversion
592 RegQueryValueEx = _winreg.QueryValueEx
593 RegOpenKeyEx = _winreg.OpenKeyEx
594 RegCloseKey = _winreg.CloseKey
595 HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
596 VER_PLATFORM_WIN32_WINDOWS = 1
597 VER_PLATFORM_WIN32_NT = 2
598 VER_NT_WORKSTATION = 1
Brian Curtina8538a52010-05-06 03:01:55 +0000599 VER_NT_SERVER = 3
600 REG_SZ = 1
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000601
602 # Find out the registry key and some general version infos
Brian Curtina8538a52010-05-06 03:01:55 +0000603 winver = GetVersionEx()
604 maj,min,buildno,plat,csd = winver
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000605 version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
Brian Curtina8538a52010-05-06 03:01:55 +0000606 if hasattr(winver, "service_pack"):
607 if winver.service_pack != "":
608 csd = 'SP%s' % winver.service_pack_major
609 else:
610 if csd[:13] == 'Service Pack ':
611 csd = 'SP' + csd[13:]
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000612 if plat == VER_PLATFORM_WIN32_WINDOWS:
613 regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
614 # Try to guess the release name
615 if maj == 4:
616 if min == 0:
617 release = '95'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000618 elif min == 10:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000619 release = '98'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000620 elif min == 90:
621 release = 'Me'
622 else:
623 release = 'postMe'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000624 elif maj == 5:
625 release = '2000'
626 elif plat == VER_PLATFORM_WIN32_NT:
627 regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
628 if maj <= 4:
629 release = 'NT'
630 elif maj == 5:
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000631 if min == 0:
632 release = '2000'
633 elif min == 1:
634 release = 'XP'
635 elif min == 2:
636 release = '2003Server'
637 else:
638 release = 'post2003'
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +0000639 elif maj == 6:
Brian Curtina8538a52010-05-06 03:01:55 +0000640 if hasattr(winver, "product_type"):
641 product_type = winver.product_type
642 else:
643 product_type = VER_NT_WORKSTATION
644 # Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
645 # or help from the registry, we cannot properly identify
646 # non-workstation versions.
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000647 try:
Brian Curtina8538a52010-05-06 03:01:55 +0000648 key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
649 name, type = RegQueryValueEx(key, "ProductName")
650 # Discard any type that isn't REG_SZ
651 if type == REG_SZ and name.find("Server") != -1:
652 product_type = VER_NT_SERVER
653 except WindowsError:
654 # Use default of VER_NT_WORKSTATION
655 pass
656
657 if min == 0:
658 if product_type == VER_NT_WORKSTATION:
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +0000659 release = 'Vista'
660 else:
Brian Curtina8538a52010-05-06 03:01:55 +0000661 release = '2008Server'
662 elif min == 1:
663 if product_type == VER_NT_WORKSTATION:
664 release = '7'
665 else:
666 release = '2008ServerR2'
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +0000667 else:
668 release = 'post2008Server'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000669 else:
670 if not release:
671 # E.g. Win3.1 with win32s
672 release = '%i.%i' % (maj,min)
673 return release,version,csd,ptype
674
675 # Open the registry key
676 try:
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000677 keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000678 # Get a value to make sure the key exists...
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +0000679 RegQueryValueEx(keyCurVer, 'SystemRoot')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000680 except:
681 return release,version,csd,ptype
Tim Peters0eadaac2003-04-24 16:02:54 +0000682
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000683 # Parse values
684 #subversion = _win32_getvalue(keyCurVer,
685 # 'SubVersionNumber',
686 # ('',1))[0]
687 #if subversion:
688 # release = release + subversion # 95a, 95b, etc.
689 build = _win32_getvalue(keyCurVer,
690 'CurrentBuildNumber',
691 ('',1))[0]
692 ptype = _win32_getvalue(keyCurVer,
693 'CurrentType',
694 (ptype,1))[0]
695
696 # Normalize version
697 version = _norm_version(version,build)
698
699 # Close key
700 RegCloseKey(keyCurVer)
701 return release,version,csd,ptype
702
703def _mac_ver_lookup(selectors,default=None):
704
705 from gestalt import gestalt
Jack Jansena290e3d2003-08-11 11:08:49 +0000706 import MacOS
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000707 l = []
708 append = l.append
709 for selector in selectors:
710 try:
711 append(gestalt(selector))
Jack Jansena290e3d2003-08-11 11:08:49 +0000712 except (RuntimeError, MacOS.Error):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000713 append(default)
714 return l
715
716def _bcd2str(bcd):
717
718 return hex(bcd)[2:]
719
Ronald Oussoren446aa632010-07-23 12:45:53 +0000720def _mac_ver_gestalt():
721 """
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000722 Thanks to Mark R. Levinson for mailing documentation links and
723 code examples for this function. Documentation for the
724 gestalt() API is available online at:
725
726 http://www.rgaros.nl/gestalt/
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000727 """
728 # Check whether the version info module is available
729 try:
730 import gestalt
Jack Jansena290e3d2003-08-11 11:08:49 +0000731 import MacOS
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000732 except ImportError:
Ronald Oussoren446aa632010-07-23 12:45:53 +0000733 return None
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000734 # Get the infos
Ronald Oussoren6ff97f72010-02-07 11:30:54 +0000735 sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000736 # Decode the infos
737 if sysv:
738 major = (sysv & 0xFF00) >> 8
739 minor = (sysv & 0x00F0) >> 4
740 patch = (sysv & 0x000F)
Ronald Oussorenc27b8b82008-05-08 10:34:39 +0000741
742 if (major, minor) >= (10, 4):
743 # the 'sysv' gestald cannot return patchlevels
744 # higher than 9. Apple introduced 3 new
745 # gestalt codes in 10.4 to deal with this
746 # issue (needed because patch levels can
747 # run higher than 9, such as 10.4.11)
748 major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
749 release = '%i.%i.%i' %(major, minor, patch)
750 else:
751 release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
Ronald Oussoren7a0f4c72008-05-18 20:54:47 +0000752
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000753 if sysa:
Tim Peters0eadaac2003-04-24 16:02:54 +0000754 machine = {0x1: '68k',
Ronald Oussoren749d0702006-04-17 13:37:15 +0000755 0x2: 'PowerPC',
756 0xa: 'i386'}.get(sysa,'')
Ronald Oussoren446aa632010-07-23 12:45:53 +0000757
758 return release,versioninfo,machine
759
760def _mac_ver_xml():
761 fn = '/System/Library/CoreServices/SystemVersion.plist'
762 if not os.path.exists(fn):
763 return None
764
765 try:
766 import plistlib
767 except ImportError:
768 return None
769
770 pl = plistlib.readPlist(fn)
771 release = pl['ProductVersion']
772 versioninfo=('', '', '')
773 machine = os.uname()[4]
Ronald Oussorenf7a13b32010-08-03 08:09:15 +0000774 if machine in ('ppc', 'Power Macintosh'):
Ronald Oussoren446aa632010-07-23 12:45:53 +0000775 # for compatibility with the gestalt based code
776 machine = 'PowerPC'
777
778 return release,versioninfo,machine
779
780
781def mac_ver(release='',versioninfo=('','',''),machine=''):
782
783 """ Get MacOS version information and return it as tuple (release,
784 versioninfo, machine) with versioninfo being a tuple (version,
785 dev_stage, non_release_version).
786
787 Entries which cannot be determined are set to the paramter values
788 which default to ''. All tuple entries are strings.
789 """
790
791 # First try reading the information from an XML file which should
792 # always be present
793 info = _mac_ver_xml()
794 if info is not None:
795 return info
796
797 # If that doesn't work for some reason fall back to reading the
798 # information using gestalt calls.
799 info = _mac_ver_gestalt()
800 if info is not None:
801 return info
802
803 # If that also doesn't work return the default values
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000804 return release,versioninfo,machine
805
Neal Norwitz9b924c62003-06-29 04:17:45 +0000806def _java_getprop(name,default):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000807
808 from java.lang import System
809 try:
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000810 value = System.getProperty(name)
811 if value is None:
812 return default
813 return value
814 except AttributeError:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000815 return default
816
817def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
Tim Peters0eadaac2003-04-24 16:02:54 +0000818
Brett Cannon8ab27df2003-08-05 03:52:04 +0000819 """ Version interface for Jython.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000820
821 Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
822 a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
823 tuple (os_name,os_version,os_arch).
824
825 Values which cannot be determined are set to the defaults
826 given as parameters (which all default to '').
827
828 """
829 # Import the needed APIs
830 try:
831 import java.lang
832 except ImportError:
833 return release,vendor,vminfo,osinfo
834
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000835 vendor = _java_getprop('java.vendor', vendor)
836 release = _java_getprop('java.version', release)
837 vm_name, vm_release, vm_vendor = vminfo
838 vm_name = _java_getprop('java.vm.name', vm_name)
839 vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
840 vm_release = _java_getprop('java.vm.version', vm_release)
841 vminfo = vm_name, vm_release, vm_vendor
842 os_name, os_version, os_arch = osinfo
843 os_arch = _java_getprop('java.os.arch', os_arch)
844 os_name = _java_getprop('java.os.name', os_name)
845 os_version = _java_getprop('java.os.version', os_version)
846 osinfo = os_name, os_version, os_arch
Tim Peters0eadaac2003-04-24 16:02:54 +0000847
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000848 return release, vendor, vminfo, osinfo
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000849
850### System name aliasing
851
852def system_alias(system,release,version):
853
854 """ Returns (system,release,version) aliased to common
855 marketing names used for some systems.
856
857 It also does some reordering of the information in some cases
858 where it would otherwise cause confusion.
859
860 """
861 if system == 'Rhapsody':
862 # Apple's BSD derivative
863 # XXX How can we determine the marketing release number ?
864 return 'MacOS X Server',system+release,version
865
866 elif system == 'SunOS':
867 # Sun's OS
868 if release < '5':
869 # These releases use the old name SunOS
870 return system,release,version
871 # Modify release (marketing release = SunOS release - 3)
872 l = string.split(release,'.')
873 if l:
874 try:
875 major = int(l[0])
876 except ValueError:
877 pass
878 else:
879 major = major - 3
880 l[0] = str(major)
881 release = string.join(l,'.')
882 if release < '6':
883 system = 'Solaris'
884 else:
885 # XXX Whatever the new SunOS marketing name is...
886 system = 'Solaris'
887
888 elif system == 'IRIX64':
889 # IRIX reports IRIX64 on platforms with 64-bit support; yet it
890 # is really a version and not a different platform, since 32-bit
891 # apps are also supported..
892 system = 'IRIX'
893 if version:
894 version = version + ' (64bit)'
895 else:
896 version = '64bit'
897
898 elif system in ('win32','win16'):
899 # In case one of the other tricks
900 system = 'Windows'
901
902 return system,release,version
903
904### Various internal helpers
905
906def _platform(*args):
907
908 """ Helper to format the platform string in a filename
909 compatible format e.g. "system-version-machine".
910 """
911 # Format the platform string
912 platform = string.join(
913 map(string.strip,
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +0000914 filter(len, args)),
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000915 '-')
916
917 # Cleanup some possible filename obstacles...
918 replace = string.replace
919 platform = replace(platform,' ','_')
920 platform = replace(platform,'/','-')
921 platform = replace(platform,'\\','-')
922 platform = replace(platform,':','-')
923 platform = replace(platform,';','-')
924 platform = replace(platform,'"','-')
925 platform = replace(platform,'(','-')
926 platform = replace(platform,')','-')
927
928 # No need to report 'unknown' information...
929 platform = replace(platform,'unknown','')
930
931 # Fold '--'s and remove trailing '-'
932 while 1:
933 cleaned = replace(platform,'--','-')
934 if cleaned == platform:
935 break
936 platform = cleaned
937 while platform[-1] == '-':
938 platform = platform[:-1]
939
940 return platform
941
942def _node(default=''):
943
944 """ Helper to determine the node name of this machine.
945 """
946 try:
947 import socket
948 except ImportError:
949 # No sockets...
950 return default
951 try:
952 return socket.gethostname()
953 except socket.error:
954 # Still not working...
955 return default
956
957# os.path.abspath is new in Python 1.5.2:
958if not hasattr(os.path,'abspath'):
959
960 def _abspath(path,
961
962 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
963 normpath=os.path.normpath):
964
965 if not isabs(path):
966 path = join(getcwd(), path)
967 return normpath(path)
968
969else:
970
971 _abspath = os.path.abspath
972
973def _follow_symlinks(filepath):
974
975 """ In case filepath is a symlink, follow it until a
976 real file is reached.
977 """
978 filepath = _abspath(filepath)
979 while os.path.islink(filepath):
980 filepath = os.path.normpath(
Hirokazu Yamamoto171c4aa2008-09-04 11:15:14 +0000981 os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000982 return filepath
983
984def _syscmd_uname(option,default=''):
985
986 """ Interface to the system's uname command.
987 """
988 if sys.platform in ('dos','win32','win16','os2'):
989 # XXX Others too ?
990 return default
991 try:
992 f = os.popen('uname %s 2> /dev/null' % option)
993 except (AttributeError,os.error):
994 return default
995 output = string.strip(f.read())
996 rc = f.close()
997 if not output or rc:
998 return default
999 else:
1000 return output
1001
1002def _syscmd_file(target,default=''):
1003
1004 """ Interface to the system's file command.
1005
1006 The function uses the -b option of the file command to have it
1007 ommit the filename in its output and if possible the -L option
1008 to have the command follow symlinks. It returns default in
1009 case the command should fail.
1010
1011 """
Hirokazu Yamamotoed8c6442008-09-01 14:32:58 +00001012 if sys.platform in ('dos','win32','win16','os2'):
1013 # XXX Others too ?
1014 return default
Ezio Melottib55d3682010-08-02 20:26:41 +00001015 target = _follow_symlinks(target).replace('"', '\\"')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001016 try:
Marc-André Lemburgd15fad72008-09-02 10:32:34 +00001017 f = os.popen('file "%s" 2> /dev/null' % target)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001018 except (AttributeError,os.error):
1019 return default
1020 output = string.strip(f.read())
1021 rc = f.close()
1022 if not output or rc:
1023 return default
1024 else:
1025 return output
1026
1027### Information about the used architecture
1028
1029# Default values for architecture; non-empty strings override the
1030# defaults given as parameters
1031_default_architecture = {
1032 'win32': ('','WindowsPE'),
1033 'win16': ('','Windows'),
1034 'dos': ('','MSDOS'),
1035}
1036
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +00001037_architecture_split = re.compile(r'[\s,]').split
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001038
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +00001039def architecture(executable=sys.executable,bits='',linkage=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001040
1041 """ Queries the given executable (defaults to the Python interpreter
Brett Cannon8ab27df2003-08-05 03:52:04 +00001042 binary) for various architecture information.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001043
Brett Cannon8ab27df2003-08-05 03:52:04 +00001044 Returns a tuple (bits,linkage) which contains information about
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001045 the bit architecture and the linkage format used for the
1046 executable. Both values are returned as strings.
1047
1048 Values that cannot be determined are returned as given by the
1049 parameter presets. If bits is given as '', the sizeof(pointer)
1050 (or sizeof(long) on Python version < 1.5.2) is used as
1051 indicator for the supported pointer size.
1052
1053 The function relies on the system's "file" command to do the
1054 actual work. This is available on most if not all Unix
Brett Cannon8ab27df2003-08-05 03:52:04 +00001055 platforms. On some non-Unix platforms where the "file" command
1056 does not exist and the executable is set to the Python interpreter
1057 binary defaults from _default_architecture are used.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001058
1059 """
1060 # Use the sizeof(pointer) as default number of bits if nothing
1061 # else is given as default.
1062 if not bits:
1063 import struct
1064 try:
1065 size = struct.calcsize('P')
1066 except struct.error:
1067 # Older installations can only query longs
1068 size = struct.calcsize('l')
1069 bits = str(size*8) + 'bit'
Tim Peters0eadaac2003-04-24 16:02:54 +00001070
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001071 # Get data from the 'file' system command
Marc-André Lemburg3b8f60b2007-01-13 23:13:54 +00001072 if executable:
1073 output = _syscmd_file(executable, '')
1074 else:
1075 output = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001076
1077 if not output and \
1078 executable == sys.executable:
1079 # "file" command did not return anything; we'll try to provide
Tim Peters0eadaac2003-04-24 16:02:54 +00001080 # some sensible defaults then...
Ezio Melottib55d3682010-08-02 20:26:41 +00001081 if sys.platform in _default_architecture:
1082 b, l = _default_architecture[sys.platform]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001083 if b:
1084 bits = b
1085 if l:
1086 linkage = l
Ezio Melottib55d3682010-08-02 20:26:41 +00001087 return bits, linkage
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001088
1089 # Split the output into a list of strings omitting the filename
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +00001090 fileout = _architecture_split(output)[1:]
Tim Peters0eadaac2003-04-24 16:02:54 +00001091
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001092 if 'executable' not in fileout:
1093 # Format not supported
1094 return bits,linkage
1095
1096 # Bits
1097 if '32-bit' in fileout:
1098 bits = '32bit'
1099 elif 'N32' in fileout:
1100 # On Irix only
1101 bits = 'n32bit'
1102 elif '64-bit' in fileout:
1103 bits = '64bit'
1104
1105 # Linkage
1106 if 'ELF' in fileout:
1107 linkage = 'ELF'
1108 elif 'PE' in fileout:
1109 # E.g. Windows uses this format
1110 if 'Windows' in fileout:
1111 linkage = 'WindowsPE'
1112 else:
1113 linkage = 'PE'
1114 elif 'COFF' in fileout:
1115 linkage = 'COFF'
1116 elif 'MS-DOS' in fileout:
1117 linkage = 'MSDOS'
1118 else:
1119 # XXX the A.OUT format also falls under this class...
1120 pass
1121
1122 return bits,linkage
1123
1124### Portable uname() interface
Tim Peters0eadaac2003-04-24 16:02:54 +00001125
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001126_uname_cache = None
1127
1128def uname():
1129
1130 """ Fairly portable uname interface. Returns a tuple
1131 of strings (system,node,release,version,machine,processor)
1132 identifying the underlying platform.
1133
1134 Note that unlike the os.uname function this also returns
Brett Cannon8ab27df2003-08-05 03:52:04 +00001135 possible processor information as an additional tuple entry.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001136
1137 Entries which cannot be determined are set to ''.
1138
1139 """
1140 global _uname_cache
Benjamin Peterson5c0be322008-06-13 15:11:50 +00001141 no_os_uname = 0
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001142
1143 if _uname_cache is not None:
1144 return _uname_cache
1145
Benjamin Peterson5c0be322008-06-13 15:11:50 +00001146 processor = ''
1147
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001148 # Get some infos from the builtin os.uname API...
1149 try:
1150 system,node,release,version,machine = os.uname()
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001151 except AttributeError:
Benjamin Peterson5c0be322008-06-13 15:11:50 +00001152 no_os_uname = 1
1153
1154 if no_os_uname or not filter(None, (system, node, release, version, machine)):
1155 # Hmm, no there is either no uname or uname has returned
1156 #'unknowns'... we'll have to poke around the system then.
1157 if no_os_uname:
1158 system = sys.platform
1159 release = ''
1160 version = ''
1161 node = _node()
1162 machine = ''
1163
1164 use_syscmd_ver = 01
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001165
1166 # Try win32_ver() on win32 platforms
1167 if system == 'win32':
1168 release,version,csd,ptype = win32_ver()
1169 if release and version:
1170 use_syscmd_ver = 0
Marc-André Lemburgdbd61a22008-03-20 17:31:36 +00001171 # Try to use the PROCESSOR_* environment variables
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001172 # available on Win XP and later; see
1173 # http://support.microsoft.com/kb/888731 and
1174 # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
Benjamin Peterson5c0be322008-06-13 15:11:50 +00001175 if not machine:
1176 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
1177 if not processor:
1178 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
Tim Peters0eadaac2003-04-24 16:02:54 +00001179
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001180 # Try the 'ver' system command available on some
1181 # platforms
1182 if use_syscmd_ver:
1183 system,release,version = _syscmd_ver(system)
Marc-André Lemburgcdc79232004-06-19 17:17:00 +00001184 # Normalize system to what win32_ver() normally returns
1185 # (_syscmd_ver() tends to return the vendor name as well)
1186 if system == 'Microsoft Windows':
1187 system = 'Windows'
Marc-André Lemburgb24cd0f2007-06-12 09:26:49 +00001188 elif system == 'Microsoft' and release == 'Windows':
1189 # Under Windows Vista and Windows Server 2008,
1190 # Microsoft changed the output of the ver command. The
1191 # release is no longer printed. This causes the
1192 # system and release to be misidentified.
1193 system = 'Windows'
1194 if '6.0' == version[:3]:
1195 release = 'Vista'
1196 else:
1197 release = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001198
1199 # In case we still don't know anything useful, we'll try to
1200 # help ourselves
1201 if system in ('win32','win16'):
1202 if not version:
1203 if system == 'win32':
1204 version = '32bit'
1205 else:
1206 version = '16bit'
1207 system = 'Windows'
1208
1209 elif system[:4] == 'java':
1210 release,vendor,vminfo,osinfo = java_ver()
1211 system = 'Java'
1212 version = string.join(vminfo,', ')
1213 if not version:
1214 version = vendor
1215
1216 elif os.name == 'mac':
1217 release,(version,stage,nonrel),machine = mac_ver()
1218 system = 'MacOS'
1219
Benjamin Peterson5c0be322008-06-13 15:11:50 +00001220 # System specific extensions
1221 if system == 'OpenVMS':
1222 # OpenVMS seems to have release and version mixed up
1223 if not release or release == '0':
1224 release = version
1225 version = ''
1226 # Get processor information
1227 try:
1228 import vms_lib
1229 except ImportError:
1230 pass
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001231 else:
Benjamin Peterson5c0be322008-06-13 15:11:50 +00001232 csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
1233 if (cpu_number >= 128):
1234 processor = 'Alpha'
1235 else:
1236 processor = 'VAX'
1237 if not processor:
1238 # Get processor information from the uname system command
1239 processor = _syscmd_uname('-p','')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001240
Benjamin Peterson5c0be322008-06-13 15:11:50 +00001241 #If any unknowns still exist, replace them with ''s, which are more portable
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001242 if system == 'unknown':
1243 system = ''
1244 if node == 'unknown':
1245 node = ''
1246 if release == 'unknown':
1247 release = ''
1248 if version == 'unknown':
1249 version = ''
1250 if machine == 'unknown':
1251 machine = ''
1252 if processor == 'unknown':
1253 processor = ''
Sean Reifscheiderf09597c2007-09-17 20:53:21 +00001254
1255 # normalize name
1256 if system == 'Microsoft' and release == 'Windows':
1257 system = 'Windows'
1258 release = 'Vista'
1259
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001260 _uname_cache = system,node,release,version,machine,processor
1261 return _uname_cache
1262
1263### Direct interfaces to some of the uname() return values
1264
1265def system():
1266
1267 """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
1268
1269 An empty string is returned if the value cannot be determined.
1270
1271 """
1272 return uname()[0]
1273
1274def node():
1275
Brett Cannon8ab27df2003-08-05 03:52:04 +00001276 """ Returns the computer's network name (which may not be fully
1277 qualified)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001278
1279 An empty string is returned if the value cannot be determined.
1280
1281 """
1282 return uname()[1]
1283
1284def release():
1285
1286 """ Returns the system's release, e.g. '2.2.0' or 'NT'
1287
1288 An empty string is returned if the value cannot be determined.
1289
1290 """
1291 return uname()[2]
1292
1293def version():
1294
1295 """ Returns the system's release version, e.g. '#3 on degas'
1296
1297 An empty string is returned if the value cannot be determined.
1298
1299 """
1300 return uname()[3]
1301
1302def machine():
1303
1304 """ Returns the machine type, e.g. 'i386'
1305
1306 An empty string is returned if the value cannot be determined.
1307
1308 """
1309 return uname()[4]
1310
1311def processor():
1312
1313 """ Returns the (true) processor name, e.g. 'amdk6'
1314
1315 An empty string is returned if the value cannot be
1316 determined. Note that many platforms do not provide this
1317 information or simply return the same value as for machine(),
1318 e.g. NetBSD does this.
1319
1320 """
1321 return uname()[5]
1322
1323### Various APIs for extracting information from sys.version
1324
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001325_sys_version_parser = re.compile(
1326 r'([\w.+]+)\s*'
1327 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
1328 '\[([^\]]+)\]?')
1329
1330_jython_sys_version_parser = re.compile(
1331 r'([\d\.]+)')
1332
1333_ironpython_sys_version_parser = re.compile(
1334 r'IronPython\s*'
1335 '([\d\.]+)'
1336 '(?: \(([\d\.]+)\))?'
1337 ' on (.NET [\d\.]+)')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001338
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001339_sys_version_cache = {}
1340
1341def _sys_version(sys_version=None):
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001342
1343 """ Returns a parsed version of Python's sys.version as tuple
Marc-André Lemburg152f2222009-03-25 19:52:04 +00001344 (name, version, branch, revision, buildno, builddate, compiler)
1345 referring to the Python implementation name, version, branch,
1346 revision, build number, build date/time as string and the compiler
1347 identification string.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001348
1349 Note that unlike the Python sys.version, the returned value
1350 for the Python version will always include the patchlevel (it
1351 defaults to '.0').
1352
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001353 The function returns empty strings for tuple entries that
1354 cannot be determined.
1355
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001356 sys_version may be given to parse an alternative version
1357 string, e.g. if the version was read from a different Python
1358 interpreter.
1359
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001360 """
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001361 # Get the Python version
1362 if sys_version is None:
1363 sys_version = sys.version
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001364
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001365 # Try the cache first
1366 result = _sys_version_cache.get(sys_version, None)
1367 if result is not None:
1368 return result
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001369
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001370 # Parse it
1371 if sys_version[:10] == 'IronPython':
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001372 # IronPython
1373 name = 'IronPython'
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001374 match = _ironpython_sys_version_parser.match(sys_version)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001375 if match is None:
1376 raise ValueError(
1377 'failed to parse IronPython sys.version: %s' %
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001378 repr(sys_version))
1379 version, alt_version, compiler = match.groups()
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001380 branch = ''
1381 revision = ''
1382 buildno = ''
1383 builddate = ''
1384
1385 elif sys.platform[:4] == 'java':
1386 # Jython
1387 name = 'Jython'
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001388 match = _jython_sys_version_parser.match(sys_version)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001389 if match is None:
1390 raise ValueError(
1391 'failed to parse Jython sys.version: %s' %
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001392 repr(sys_version))
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001393 version, = match.groups()
1394 branch = ''
1395 revision = ''
1396 compiler = sys.platform
1397 buildno = ''
1398 builddate = ''
1399
1400 else:
1401 # CPython
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001402 match = _sys_version_parser.match(sys_version)
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001403 if match is None:
1404 raise ValueError(
1405 'failed to parse CPython sys.version: %s' %
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001406 repr(sys_version))
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001407 version, buildno, builddate, buildtime, compiler = \
1408 match.groups()
1409 if hasattr(sys, 'subversion'):
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001410 # sys.subversion was added in Python 2.5
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001411 name, branch, revision = sys.subversion
1412 else:
1413 name = 'CPython'
1414 branch = ''
1415 revision = ''
1416 builddate = builddate + ' ' + buildtime
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001417
1418 # Add the patchlevel version if missing
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001419 l = string.split(version, '.')
1420 if len(l) == 2:
1421 l.append('0')
1422 version = string.join(l, '.')
Marc-André Lemburg2be9d432007-01-13 22:32:21 +00001423
1424 # Build and cache the result
1425 result = (name, version, branch, revision, buildno, builddate, compiler)
1426 _sys_version_cache[sys_version] = result
1427 return result
1428
1429def _test_sys_version():
1430
1431 _sys_version_cache.clear()
1432 for input, output in (
1433 ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
1434 ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
1435 ('IronPython 1.0.60816 on .NET 2.0.50727.42',
1436 ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
1437 ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
1438 ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
1439 ):
1440 parsed = _sys_version(input)
1441 if parsed != output:
1442 print (input, parsed)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001443
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001444def python_implementation():
1445
1446 """ Returns a string identifying the Python implementation.
1447
1448 Currently, the following implementations are identified:
1449 'CPython' (C implementation of Python),
1450 'IronPython' (.NET implementation of Python),
1451 'Jython' (Java implementation of Python).
1452
1453 """
1454 return _sys_version()[0]
1455
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001456def python_version():
1457
1458 """ Returns the Python version as string 'major.minor.patchlevel'
1459
1460 Note that unlike the Python sys.version, the returned value
1461 will always include the patchlevel (it defaults to 0).
1462
1463 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001464 return _sys_version()[1]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001465
1466def python_version_tuple():
1467
1468 """ Returns the Python version as tuple (major, minor, patchlevel)
1469 of strings.
1470
1471 Note that unlike the Python sys.version, the returned value
1472 will always include the patchlevel (it defaults to 0).
1473
1474 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001475 return tuple(string.split(_sys_version()[1], '.'))
1476
1477def python_branch():
1478
Neal Norwitz4b86f8b2007-01-13 21:22:37 +00001479 """ Returns a string identifying the Python implementation
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001480 branch.
1481
1482 For CPython this is the Subversion branch from which the
1483 Python binary was built.
1484
1485 If not available, an empty string is returned.
1486
1487 """
Tim Petersf733abb2007-01-30 03:03:46 +00001488
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001489 return _sys_version()[2]
1490
1491def python_revision():
1492
Neal Norwitz4b86f8b2007-01-13 21:22:37 +00001493 """ Returns a string identifying the Python implementation
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001494 revision.
1495
1496 For CPython this is the Subversion revision from which the
1497 Python binary was built.
1498
1499 If not available, an empty string is returned.
1500
1501 """
1502 return _sys_version()[3]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001503
1504def python_build():
1505
1506 """ Returns a tuple (buildno, builddate) stating the Python
1507 build number and date as strings.
1508
1509 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001510 return _sys_version()[4:6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001511
1512def python_compiler():
1513
1514 """ Returns a string identifying the compiler used for compiling
1515 Python.
1516
1517 """
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001518 return _sys_version()[6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001519
1520### The Opus Magnum of platform strings :-)
1521
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001522_platform_cache = {}
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001523
1524def platform(aliased=0, terse=0):
1525
1526 """ Returns a single string identifying the underlying platform
1527 with as much useful information as possible (but no more :).
Tim Peters0eadaac2003-04-24 16:02:54 +00001528
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001529 The output is intended to be human readable rather than
1530 machine parseable. It may look different on different
1531 platforms and this is intended.
1532
1533 If "aliased" is true, the function will use aliases for
1534 various platforms that report system names which differ from
1535 their common names, e.g. SunOS will be reported as
1536 Solaris. The system_alias() function is used to implement
1537 this.
1538
1539 Setting terse to true causes the function to return only the
1540 absolute minimum information needed to identify the platform.
1541
1542 """
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001543 result = _platform_cache.get((aliased, terse), None)
1544 if result is not None:
1545 return result
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001546
1547 # Get uname information and then apply platform specific cosmetics
1548 # to it...
1549 system,node,release,version,machine,processor = uname()
1550 if machine == processor:
1551 processor = ''
1552 if aliased:
1553 system,release,version = system_alias(system,release,version)
1554
1555 if system == 'Windows':
1556 # MS platforms
1557 rel,vers,csd,ptype = win32_ver(version)
1558 if terse:
1559 platform = _platform(system,release)
1560 else:
1561 platform = _platform(system,release,version,csd)
1562
1563 elif system in ('Linux',):
1564 # Linux based systems
1565 distname,distversion,distid = dist('')
1566 if distname and not terse:
1567 platform = _platform(system,release,machine,processor,
1568 'with',
1569 distname,distversion,distid)
1570 else:
1571 # If the distribution name is unknown check for libc vs. glibc
1572 libcname,libcversion = libc_ver(sys.executable)
1573 platform = _platform(system,release,machine,processor,
1574 'with',
1575 libcname+libcversion)
1576 elif system == 'Java':
1577 # Java platforms
1578 r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
Marc-André Lemburg9e0dc962007-01-13 21:00:08 +00001579 if terse or not os_name:
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001580 platform = _platform(system,release,version)
1581 else:
1582 platform = _platform(system,release,version,
1583 'on',
1584 os_name,os_version,os_arch)
1585
1586 elif system == 'MacOS':
1587 # MacOS platforms
1588 if terse:
1589 platform = _platform(system,release)
1590 else:
1591 platform = _platform(system,release,machine)
1592
1593 else:
1594 # Generic handler
1595 if terse:
1596 platform = _platform(system,release)
1597 else:
1598 bits,linkage = architecture(sys.executable)
1599 platform = _platform(system,release,machine,processor,bits,linkage)
Tim Peters0eadaac2003-04-24 16:02:54 +00001600
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001601 _platform_cache[(aliased, terse)] = platform
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001602 return platform
1603
1604### Command line interface
1605
1606if __name__ == '__main__':
1607 # Default is to print the aliased verbose platform string
Tim Peters0eadaac2003-04-24 16:02:54 +00001608 terse = ('terse' in sys.argv or '--terse' in sys.argv)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001609 aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
1610 print platform(aliased,terse)
1611 sys.exit(0)