blob: 45546599b4e835fd8ba316b91d42fc65279fca7a [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Marc-André Lemburg246d8472003-04-24 11:36:11 +00002
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
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000013# Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
Marc-André Lemburg246d8472003-04-24 11:36:11 +000014#
Marc-André Lemburg246d8472003-04-24 11:36:11 +000015# Still needed:
16# * more support for WinCE
17# * support for MS-DOS (PythonDX ?)
18# * support for Amiga and other still unsupported platforms running Python
19# * support for additional Linux distributions
20#
Brett Cannon8ab27df2003-08-05 03:52:04 +000021# Many thanks to all those who helped adding platform-specific
Marc-André Lemburg246d8472003-04-24 11:36:11 +000022# checks (in no particular order):
23#
24# Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
25# Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
26# Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
27# Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
28# Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000029# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
Marc-André Lemburg246d8472003-04-24 11:36:11 +000030#
31# History:
Marc-André Lemburg380f4172005-11-07 16:11:02 +000032#
33# <see CVS and SVN checkin messages for history>
34#
Alexandre Vassalottie52e3782009-07-17 09:18:18 +000035# 1.0.7 - added DEV_NULL
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000036# 1.0.6 - added linux_distribution()
37# 1.0.5 - fixed Java support to allow running the module on Jython
38# 1.0.4 - added IronPython support
Marc-André Lemburgcdc79232004-06-19 17:17:00 +000039# 1.0.3 - added normalization of Windows system name
Marc-André Lemburg91e83e22004-03-25 18:35:12 +000040# 1.0.2 - added more Windows support
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +000041# 1.0.1 - reformatted to make doc.py happy
Marc-André Lemburg246d8472003-04-24 11:36:11 +000042# 1.0.0 - reformatted a bit and checked into Python CVS
43# 0.8.0 - added sys.version parser and various new access
44# APIs (python_version(), python_compiler(), etc.)
45# 0.7.2 - fixed architecture() to use sizeof(pointer) where available
46# 0.7.1 - added support for Caldera OpenLinux
47# 0.7.0 - some fixes for WinCE; untabified the source file
48# 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
49# vms_lib.getsyi() configured
50# 0.6.1 - added code to prevent 'uname -p' on platforms which are
51# known not to support it
52# 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
53# did some cleanup of the interfaces - some APIs have changed
54# 0.5.5 - fixed another type in the MacOS code... should have
55# used more coffee today ;-)
56# 0.5.4 - fixed a few typos in the MacOS code
57# 0.5.3 - added experimental MacOS support; added better popen()
58# workarounds in _syscmd_ver() -- still not 100% elegant
59# though
60# 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
61# return values (the system uname command tends to return
62# 'unknown' instead of just leaving the field emtpy)
63# 0.5.1 - included code for slackware dist; added exception handlers
64# to cover up situations where platforms don't have os.popen
65# (e.g. Mac) or fail on socket.gethostname(); fixed libc
66# detection RE
67# 0.5.0 - changed the API names referring to system commands to *syscmd*;
68# added java_ver(); made syscmd_ver() a private
69# API (was system_ver() in previous versions) -- use uname()
70# instead; extended the win32_ver() to also return processor
71# type information
72# 0.4.0 - added win32_ver() and modified the platform() output for WinXX
73# 0.3.4 - fixed a bug in _follow_symlinks()
74# 0.3.3 - fixed popen() and "file" command invokation bugs
75# 0.3.2 - added architecture() API and support for it in platform()
76# 0.3.1 - fixed syscmd_ver() RE to support Windows NT
77# 0.3.0 - added system alias support
78# 0.2.3 - removed 'wince' again... oh well.
79# 0.2.2 - added 'wince' to syscmd_ver() supported platforms
80# 0.2.1 - added cache logic and changed the platform string format
81# 0.2.0 - changed the API to use functions instead of module globals
82# since some action take too long to be run on module import
83# 0.1.0 - first release
84#
85# You can always get the latest version of this module at:
86#
87# http://www.egenix.com/files/python/platform.py
88#
89# If that URL should fail, try contacting the author.
90
91__copyright__ = """
92 Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
Benjamin Peterson46a99002010-01-09 18:45:30 +000093 Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
Marc-André Lemburg246d8472003-04-24 11:36:11 +000094
95 Permission to use, copy, modify, and distribute this software and its
96 documentation for any purpose and without fee or royalty is hereby granted,
97 provided that the above copyright notice appear in all copies and that
98 both that copyright notice and this permission notice appear in
99 supporting documentation or portions thereof, including modifications,
100 that you make.
101
102 EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
103 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
104 FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
105 INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
106 FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
107 NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
108 WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
109
110"""
111
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000112__version__ = '1.0.7'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000113
Victor Stinnerb27ee202010-04-18 18:28:09 +0000114import sys, os, re
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000115
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000116### Globals & Constants
117
118# Determine the platform's /dev/null device
119try:
120 DEV_NULL = os.devnull
121except AttributeError:
122 # os.devnull was added in Python 2.4, so emulate it for earlier
123 # Python versions
124 if sys.platform in ('dos','win32','win16','os2'):
125 # Use the old CP/M NUL as device name
126 DEV_NULL = 'NUL'
127 else:
128 # Standard Unix uses /dev/null
129 DEV_NULL = '/dev/null'
130
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000131### Platform specific APIs
132
Antoine Pitrouba7c2262011-10-07 13:26:59 +0200133_libc_search = re.compile(b'(__libc_init)'
134 b'|'
135 b'(GLIBC_([0-9.]+))'
136 b'|'
137 br'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)', re.ASCII)
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000138
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000139def libc_ver(executable=sys.executable,lib='',version='',
140
Antoine Pitrouba7c2262011-10-07 13:26:59 +0200141 chunksize=16384):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000142
Brett Cannon8ab27df2003-08-05 03:52:04 +0000143 """ Tries to determine the libc version that the file executable
144 (which defaults to the Python interpreter) is linked against.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000145
146 Returns a tuple of strings (lib,version) which default to the
147 given parameters in case the lookup fails.
148
149 Note that the function has intimate knowledge of how different
Brett Cannon8ab27df2003-08-05 03:52:04 +0000150 libc versions add symbols to the executable and thus is probably
151 only useable for executables compiled using gcc.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000152
153 The file is read and scanned in chunks of chunksize bytes.
154
155 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000156 if hasattr(os.path, 'realpath'):
157 # Python 2.2 introduced os.path.realpath(); it is used
158 # here to work around problems with Cygwin not being
159 # able to open symlinks for reading
160 executable = os.path.realpath(executable)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000161 f = open(executable,'rb')
Antoine Pitrouba7c2262011-10-07 13:26:59 +0200162 binary = f.read(chunksize)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000163 pos = 0
164 while 1:
Antoine Pitrouba7c2262011-10-07 13:26:59 +0200165 if b'libc' in binary or b'GLIBC' in binary:
166 m = _libc_search.search(binary,pos)
167 else:
168 m = None
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000169 if not m:
Antoine Pitrouba7c2262011-10-07 13:26:59 +0200170 binary = f.read(chunksize)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000171 if not binary:
172 break
173 pos = 0
174 continue
Antoine Pitrouba7c2262011-10-07 13:26:59 +0200175 libcinit,glibc,glibcversion,so,threads,soversion = [
176 s.decode('latin1') if s is not None else s
177 for s in m.groups()]
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000178 if libcinit and not lib:
179 lib = 'libc'
180 elif glibc:
181 if lib != 'glibc':
182 lib = 'glibc'
183 version = glibcversion
184 elif glibcversion > version:
185 version = glibcversion
186 elif so:
187 if lib != 'glibc':
188 lib = 'libc'
Victor Stinner87448812011-12-15 21:42:03 +0100189 if soversion and soversion > version:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000190 version = soversion
191 if threads and version[-len(threads):] != threads:
192 version = version + threads
193 pos = m.end()
194 f.close()
195 return lib,version
196
197def _dist_try_harder(distname,version,id):
198
Tim Peters0eadaac2003-04-24 16:02:54 +0000199 """ Tries some special tricks to get the distribution
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000200 information in case the default method fails.
201
202 Currently supports older SuSE Linux, Caldera OpenLinux and
203 Slackware Linux distributions.
204
205 """
206 if os.path.exists('/var/adm/inst-log/info'):
207 # SuSE Linux stores distribution information in that file
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000208 distname = 'SuSE'
Florent Xicluna7dde7922010-09-03 19:52:03 +0000209 for line in open('/var/adm/inst-log/info'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000210 tv = line.split()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000211 if len(tv) == 2:
212 tag,value = tv
213 else:
214 continue
215 if tag == 'MIN_DIST_VERSION':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000216 version = value.strip()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000217 elif tag == 'DIST_IDENT':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000218 values = value.split('-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000219 id = values[2]
220 return distname,version,id
221
222 if os.path.exists('/etc/.installed'):
223 # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
Florent Xicluna7dde7922010-09-03 19:52:03 +0000224 for line in open('/etc/.installed'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000225 pkg = line.split('-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000226 if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
227 # XXX does Caldera support non Intel platforms ? If yes,
228 # where can we find the needed id ?
229 return 'OpenLinux',pkg[1],id
230
231 if os.path.isdir('/usr/lib/setup'):
232 # Check for slackware verson tag file (thanks to Greg Andruk)
233 verfiles = os.listdir('/usr/lib/setup')
Guido van Rossum843c7342004-05-04 18:18:59 +0000234 for n in range(len(verfiles)-1, -1, -1):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000235 if verfiles[n][:14] != 'slack-version-':
236 del verfiles[n]
237 if verfiles:
238 verfiles.sort()
239 distname = 'slackware'
240 version = verfiles[-1][14:]
241 return distname,version,id
242
243 return distname,version,id
244
Antoine Pitroufd036452008-08-19 17:56:33 +0000245_release_filename = re.compile(r'(\w+)[-_](release|version)', re.ASCII)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000246_lsb_release_version = re.compile(r'(.+)'
247 ' release '
248 '([\d.]+)'
Antoine Pitroufd036452008-08-19 17:56:33 +0000249 '[^(]*(?:\((.+)\))?', re.ASCII)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000250_release_version = re.compile(r'([^0-9]+)'
251 '(?: release )?'
252 '([\d.]+)'
Antoine Pitroufd036452008-08-19 17:56:33 +0000253 '[^(]*(?:\((.+)\))?', re.ASCII)
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000254
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000255# See also http://www.novell.com/coolsolutions/feature/11251.html
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000256# and http://linuxmafia.com/faq/Admin/release-files.html
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000257# and http://data.linux-ntfs.org/rpm/whichrpm
258# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
Marc-André Lemburg380f4172005-11-07 16:11:02 +0000259
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000260_supported_dists = (
261 'SuSE', 'debian', 'fedora', 'redhat', 'centos',
262 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
263 'UnitedLinux', 'turbolinux')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000264
265def _parse_release_file(firstline):
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000266
Benjamin Peterson25001472010-01-25 03:37:42 +0000267 # Default to empty 'version' and 'id' strings. Both defaults are used
268 # when 'firstline' is empty. 'id' defaults to empty when an id can not
269 # be deduced.
270 version = ''
271 id = ''
272
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000273 # Parse the first line
274 m = _lsb_release_version.match(firstline)
275 if m is not None:
276 # LSB format: "distro release x.x (codename)"
277 return tuple(m.groups())
278
279 # Pre-LSB format: "distro x.x (codename)"
280 m = _release_version.match(firstline)
281 if m is not None:
282 return tuple(m.groups())
283
284 # Unkown format... take the first two words
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000285 l = firstline.strip().split()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000286 if l:
287 version = l[0]
288 if len(l) > 1:
289 id = l[1]
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000290 return '', version, id
291
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000292def linux_distribution(distname='', version='', id='',
293
294 supported_dists=_supported_dists,
295 full_distribution_name=1):
296
297 """ Tries to determine the name of the Linux OS distribution name.
298
299 The function first looks for a distribution release file in
300 /etc and then reverts to _dist_try_harder() in case no
301 suitable files are found.
302
303 supported_dists may be given to define the set of Linux
304 distributions to look for. It defaults to a list of currently
305 supported Linux distributions identified by their release file
306 name.
307
308 If full_distribution_name is true (default), the full
309 distribution read from the OS is returned. Otherwise the short
310 name taken from supported_dists is used.
311
312 Returns a tuple (distname,version,id) which default to the
313 args given as parameters.
314
315 """
316 try:
317 etc = os.listdir('/etc')
318 except os.error:
319 # Probably not a Unix system
320 return distname,version,id
321 etc.sort()
322 for file in etc:
323 m = _release_filename.match(file)
324 if m is not None:
325 _distname,dummy = m.groups()
326 if _distname in supported_dists:
327 distname = _distname
328 break
329 else:
330 return _dist_try_harder(distname,version,id)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000331
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000332 # Read the first line
Florent Xicluna7dde7922010-09-03 19:52:03 +0000333 with open('/etc/'+file, 'r') as f:
334 firstline = f.readline()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000335 _distname, _version, _id = _parse_release_file(firstline)
336
337 if _distname and full_distribution_name:
338 distname = _distname
339 if _version:
340 version = _version
341 if _id:
342 id = _id
343 return distname, version, id
344
345# To maintain backwards compatibility:
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000346
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000347def dist(distname='',version='',id='',
348
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000349 supported_dists=_supported_dists):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000350
Brett Cannon8ab27df2003-08-05 03:52:04 +0000351 """ Tries to determine the name of the Linux OS distribution name.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000352
353 The function first looks for a distribution release file in
354 /etc and then reverts to _dist_try_harder() in case no
355 suitable files are found.
356
Brett Cannon8ab27df2003-08-05 03:52:04 +0000357 Returns a tuple (distname,version,id) which default to the
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000358 args given as parameters.
359
360 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000361 return linux_distribution(distname, version, id,
362 supported_dists=supported_dists,
363 full_distribution_name=0)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000364
Antoine Pitrou877766d2011-03-19 17:00:37 +0100365def popen(cmd, mode='r', bufsize=-1):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000366
367 """ Portable popen() interface.
368 """
Victor Stinner25000d42011-05-24 00:16:16 +0200369 import warnings
370 warnings.warn('use os.popen instead', DeprecationWarning, stacklevel=2)
Victor Stinner1dfd3802011-03-03 12:54:07 +0000371 return os.popen(cmd, mode, bufsize)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000372
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000373def _norm_version(version, build=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000374
Brett Cannon8ab27df2003-08-05 03:52:04 +0000375 """ Normalize the version and build strings and return a single
Walter Dörwalde5a7fad2005-11-21 17:01:27 +0000376 version string using the format major.minor.build (or patchlevel).
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000377 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000378 l = version.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000379 if build:
380 l.append(build)
381 try:
382 ints = map(int,l)
383 except ValueError:
384 strings = l
385 else:
Neal Norwitz78a70bd2007-08-30 06:16:26 +0000386 strings = list(map(str,ints))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000387 version = '.'.join(strings[:3])
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000388 return version
389
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000390_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
391 '.*'
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000392 '\[.* ([\d.]+)\])')
393
394# Examples of VER command output:
395#
396# Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
397# Windows XP: Microsoft Windows XP [Version 5.1.2600]
398# Windows Vista: Microsoft Windows [Version 6.0.6002]
399#
400# Note that the "Version" string gets localized on different
401# Windows versions.
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000402
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000403def _syscmd_ver(system='', release='', version='',
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000404
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000405 supported_platforms=('win32','win16','dos','os2')):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000406
407 """ Tries to figure out the OS version used and returns
408 a tuple (system,release,version).
Tim Peters0eadaac2003-04-24 16:02:54 +0000409
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000410 It uses the "ver" shell command for this which is known
411 to exists on Windows, DOS and OS/2. XXX Others too ?
412
413 In case this fails, the given parameters are used as
414 defaults.
415
416 """
417 if sys.platform not in supported_platforms:
418 return system,release,version
419
420 # Try some common cmd strings
421 for cmd in ('ver','command /c ver','cmd /c ver'):
422 try:
423 pipe = popen(cmd)
424 info = pipe.read()
425 if pipe.close():
Collin Winterce36ad82007-08-30 01:19:48 +0000426 raise os.error('command failed')
Ezio Melotti13925002011-03-16 11:05:33 +0200427 # XXX How can I suppress shell errors from being written
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000428 # to stderr ?
Guido van Rossumb940e112007-01-10 16:19:56 +0000429 except os.error as why:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000430 #print 'Command %s failed: %s' % (cmd,why)
431 continue
Guido van Rossumb940e112007-01-10 16:19:56 +0000432 except IOError as why:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000433 #print 'Command %s failed: %s' % (cmd,why)
434 continue
435 else:
436 break
437 else:
438 return system,release,version
439
440 # Parse the output
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000441 info = info.strip()
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000442 m = _ver_output.match(info)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000443 if m is not None:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000444 system,release,version = m.groups()
445 # Strip trailing dots from version and release
446 if release[-1] == '.':
447 release = release[:-1]
448 if version[-1] == '.':
449 version = version[:-1]
450 # Normalize the version and build strings (eliminating additional
451 # zeros)
452 version = _norm_version(version)
453 return system,release,version
454
455def _win32_getvalue(key,name,default=''):
456
457 """ Read a value for name from the registry key.
458
459 In case this fails, default is returned.
460
461 """
Christian Heimes02781dc2008-03-21 01:11:52 +0000462 try:
463 # Use win32api if available
464 from win32api import RegQueryValueEx
465 except ImportError:
Georg Brandl38feaf02008-05-25 07:45:51 +0000466 # On Python 2.0 and later, emulate using winreg
467 import winreg
468 RegQueryValueEx = winreg.QueryValueEx
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000469 try:
470 return RegQueryValueEx(key,name)
471 except:
472 return default
473
474def win32_ver(release='',version='',csd='',ptype=''):
475
476 """ Get additional version information from the Windows Registry
477 and return a tuple (version,csd,ptype) referring to version
Brian Curtin10dda6e2012-02-01 15:14:00 -0600478 number, CSD level (service pack), and OS type (multi/single
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000479 processor).
480
481 As a hint: ptype returns 'Uniprocessor Free' on single
482 processor NT machines and 'Multiprocessor Free' on multi
483 processor machines. The 'Free' refers to the OS version being
484 free of debugging code. It could also state 'Checked' which
485 means the OS version uses debugging code, i.e. code that
486 checks arguments, ranges, etc. (Thomas Heller).
487
Christian Heimes02781dc2008-03-21 01:11:52 +0000488 Note: this function works best with Mark Hammond's win32
489 package installed, but also on Python 2.3 and later. It
490 obviously only runs on Win32 compatible platforms.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000491
492 """
493 # XXX Is there any way to find out the processor type on WinXX ?
494 # XXX Is win32 available on Windows CE ?
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000495 #
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000496 # Adapted from code posted by Karl Putland to comp.lang.python.
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000497 #
498 # The mappings between reg. values and release names can be found
499 # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000500
501 # Import the needed APIs
502 try:
503 import win32api
Christian Heimes02781dc2008-03-21 01:11:52 +0000504 from win32api import RegQueryValueEx, RegOpenKeyEx, \
505 RegCloseKey, GetVersionEx
506 from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
507 VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000508 except ImportError:
Christian Heimes02781dc2008-03-21 01:11:52 +0000509 # Emulate the win32api module using Python APIs
510 try:
511 sys.getwindowsversion
512 except AttributeError:
513 # No emulation possible, so return the defaults...
514 return release,version,csd,ptype
515 else:
Georg Brandl38feaf02008-05-25 07:45:51 +0000516 # Emulation using winreg (added in Python 2.0) and
Christian Heimes02781dc2008-03-21 01:11:52 +0000517 # sys.getwindowsversion() (added in Python 2.3)
Georg Brandl38feaf02008-05-25 07:45:51 +0000518 import winreg
Christian Heimes02781dc2008-03-21 01:11:52 +0000519 GetVersionEx = sys.getwindowsversion
Georg Brandl38feaf02008-05-25 07:45:51 +0000520 RegQueryValueEx = winreg.QueryValueEx
521 RegOpenKeyEx = winreg.OpenKeyEx
522 RegCloseKey = winreg.CloseKey
523 HKEY_LOCAL_MACHINE = winreg.HKEY_LOCAL_MACHINE
Christian Heimes02781dc2008-03-21 01:11:52 +0000524 VER_PLATFORM_WIN32_WINDOWS = 1
525 VER_PLATFORM_WIN32_NT = 2
526 VER_NT_WORKSTATION = 1
Brian Curtin6e2824d2010-05-06 03:05:50 +0000527 VER_NT_SERVER = 3
528 REG_SZ = 1
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000529
530 # Find out the registry key and some general version infos
Brian Curtin6e2824d2010-05-06 03:05:50 +0000531 winver = GetVersionEx()
532 maj,min,buildno,plat,csd = winver
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000533 version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
Brian Curtin6e2824d2010-05-06 03:05:50 +0000534 if hasattr(winver, "service_pack"):
535 if winver.service_pack != "":
536 csd = 'SP%s' % winver.service_pack_major
537 else:
538 if csd[:13] == 'Service Pack ':
539 csd = 'SP' + csd[13:]
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000540
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000541 if plat == VER_PLATFORM_WIN32_WINDOWS:
542 regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
543 # Try to guess the release name
544 if maj == 4:
545 if min == 0:
546 release = '95'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000547 elif min == 10:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000548 release = '98'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000549 elif min == 90:
550 release = 'Me'
551 else:
552 release = 'postMe'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000553 elif maj == 5:
554 release = '2000'
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000555
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000556 elif plat == VER_PLATFORM_WIN32_NT:
557 regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
558 if maj <= 4:
559 release = 'NT'
560 elif maj == 5:
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000561 if min == 0:
562 release = '2000'
563 elif min == 1:
564 release = 'XP'
565 elif min == 2:
566 release = '2003Server'
567 else:
568 release = 'post2003'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000569 elif maj == 6:
Brian Curtin6e2824d2010-05-06 03:05:50 +0000570 if hasattr(winver, "product_type"):
571 product_type = winver.product_type
572 else:
573 product_type = VER_NT_WORKSTATION
574 # Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
575 # or help from the registry, we cannot properly identify
576 # non-workstation versions.
Christian Heimes02781dc2008-03-21 01:11:52 +0000577 try:
Brian Curtin6e2824d2010-05-06 03:05:50 +0000578 key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
579 name, type = RegQueryValueEx(key, "ProductName")
580 # Discard any type that isn't REG_SZ
581 if type == REG_SZ and name.find("Server") != -1:
582 product_type = VER_NT_SERVER
583 except WindowsError:
584 # Use default of VER_NT_WORKSTATION
585 pass
586
587 if min == 0:
588 if product_type == VER_NT_WORKSTATION:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000589 release = 'Vista'
590 else:
Brian Curtin6e2824d2010-05-06 03:05:50 +0000591 release = '2008Server'
592 elif min == 1:
593 if product_type == VER_NT_WORKSTATION:
594 release = '7'
595 else:
596 release = '2008ServerR2'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000597 else:
598 release = 'post2008Server'
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000599
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000600 else:
601 if not release:
602 # E.g. Win3.1 with win32s
603 release = '%i.%i' % (maj,min)
604 return release,version,csd,ptype
605
606 # Open the registry key
607 try:
Christian Heimes02781dc2008-03-21 01:11:52 +0000608 keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000609 # Get a value to make sure the key exists...
Christian Heimes02781dc2008-03-21 01:11:52 +0000610 RegQueryValueEx(keyCurVer, 'SystemRoot')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000611 except:
612 return release,version,csd,ptype
Tim Peters0eadaac2003-04-24 16:02:54 +0000613
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000614 # Parse values
615 #subversion = _win32_getvalue(keyCurVer,
616 # 'SubVersionNumber',
617 # ('',1))[0]
618 #if subversion:
619 # release = release + subversion # 95a, 95b, etc.
620 build = _win32_getvalue(keyCurVer,
621 'CurrentBuildNumber',
622 ('',1))[0]
623 ptype = _win32_getvalue(keyCurVer,
624 'CurrentType',
625 (ptype,1))[0]
626
627 # Normalize version
628 version = _norm_version(version,build)
629
630 # Close key
631 RegCloseKey(keyCurVer)
632 return release,version,csd,ptype
633
634def _mac_ver_lookup(selectors,default=None):
635
Benjamin Petersonebacd262008-05-29 21:09:51 +0000636 from _gestalt import gestalt
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000637 l = []
638 append = l.append
639 for selector in selectors:
640 try:
641 append(gestalt(selector))
Benjamin Petersonebacd262008-05-29 21:09:51 +0000642 except (RuntimeError, OSError):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000643 append(default)
644 return l
645
646def _bcd2str(bcd):
647
648 return hex(bcd)[2:]
649
Ronald Oussorene186e382010-07-23 11:54:59 +0000650def _mac_ver_gestalt():
651 """
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000652 Thanks to Mark R. Levinson for mailing documentation links and
653 code examples for this function. Documentation for the
654 gestalt() API is available online at:
655
656 http://www.rgaros.nl/gestalt/
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000657 """
658 # Check whether the version info module is available
659 try:
Benjamin Petersonebacd262008-05-29 21:09:51 +0000660 import _gestalt
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000661 except ImportError:
Ronald Oussorene186e382010-07-23 11:54:59 +0000662 return None
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000663 # Get the infos
Ronald Oussoren19258d52010-02-07 11:33:33 +0000664 sysv, sysa = _mac_ver_lookup(('sysv','sysa'))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000665 # Decode the infos
666 if sysv:
667 major = (sysv & 0xFF00) >> 8
668 minor = (sysv & 0x00F0) >> 4
669 patch = (sysv & 0x000F)
Christian Heimese4ca8152008-05-08 17:18:53 +0000670
671 if (major, minor) >= (10, 4):
672 # the 'sysv' gestald cannot return patchlevels
673 # higher than 9. Apple introduced 3 new
674 # gestalt codes in 10.4 to deal with this
675 # issue (needed because patch levels can
676 # run higher than 9, such as 10.4.11)
677 major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
678 release = '%i.%i.%i' %(major, minor, patch)
679 else:
680 release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
Benjamin Peterson856ff5f2008-05-29 21:22:40 +0000681
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000682 if sysa:
Tim Peters0eadaac2003-04-24 16:02:54 +0000683 machine = {0x1: '68k',
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000684 0x2: 'PowerPC',
685 0xa: 'i386'}.get(sysa,'')
Ronald Oussorene186e382010-07-23 11:54:59 +0000686
Ned Deily58e33502011-07-13 15:07:04 -0700687 versioninfo=('', '', '')
Ronald Oussorene186e382010-07-23 11:54:59 +0000688 return release,versioninfo,machine
689
690def _mac_ver_xml():
691 fn = '/System/Library/CoreServices/SystemVersion.plist'
692 if not os.path.exists(fn):
693 return None
694
695 try:
696 import plistlib
697 except ImportError:
698 return None
699
700 pl = plistlib.readPlist(fn)
701 release = pl['ProductVersion']
702 versioninfo=('', '', '')
703 machine = os.uname()[4]
Ronald Oussorenfcd77012010-08-03 07:42:42 +0000704 if machine in ('ppc', 'Power Macintosh'):
Ronald Oussorene186e382010-07-23 11:54:59 +0000705 # for compatibility with the gestalt based code
706 machine = 'PowerPC'
707
708 return release,versioninfo,machine
709
710
711def mac_ver(release='',versioninfo=('','',''),machine=''):
712
713 """ Get MacOS version information and return it as tuple (release,
714 versioninfo, machine) with versioninfo being a tuple (version,
715 dev_stage, non_release_version).
716
717 Entries which cannot be determined are set to the paramter values
718 which default to ''. All tuple entries are strings.
719 """
720
721 # First try reading the information from an XML file which should
722 # always be present
723 info = _mac_ver_xml()
724 if info is not None:
725 return info
726
727 # If that doesn't work for some reason fall back to reading the
728 # information using gestalt calls.
729 info = _mac_ver_gestalt()
730 if info is not None:
731 return info
732
733 # If that also doesn't work return the default values
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000734 return release,versioninfo,machine
735
Neal Norwitz9b924c62003-06-29 04:17:45 +0000736def _java_getprop(name,default):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000737
738 from java.lang import System
739 try:
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000740 value = System.getProperty(name)
741 if value is None:
742 return default
743 return value
744 except AttributeError:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000745 return default
746
747def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
Tim Peters0eadaac2003-04-24 16:02:54 +0000748
Brett Cannon8ab27df2003-08-05 03:52:04 +0000749 """ Version interface for Jython.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000750
751 Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
752 a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
753 tuple (os_name,os_version,os_arch).
754
755 Values which cannot be determined are set to the defaults
756 given as parameters (which all default to '').
757
758 """
759 # Import the needed APIs
760 try:
761 import java.lang
762 except ImportError:
763 return release,vendor,vminfo,osinfo
764
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000765 vendor = _java_getprop('java.vendor', vendor)
766 release = _java_getprop('java.version', release)
767 vm_name, vm_release, vm_vendor = vminfo
768 vm_name = _java_getprop('java.vm.name', vm_name)
769 vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
770 vm_release = _java_getprop('java.vm.version', vm_release)
771 vminfo = vm_name, vm_release, vm_vendor
772 os_name, os_version, os_arch = osinfo
773 os_arch = _java_getprop('java.os.arch', os_arch)
774 os_name = _java_getprop('java.os.name', os_name)
775 os_version = _java_getprop('java.os.version', os_version)
776 osinfo = os_name, os_version, os_arch
Tim Peters0eadaac2003-04-24 16:02:54 +0000777
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000778 return release, vendor, vminfo, osinfo
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000779
780### System name aliasing
781
782def system_alias(system,release,version):
783
784 """ Returns (system,release,version) aliased to common
785 marketing names used for some systems.
786
787 It also does some reordering of the information in some cases
788 where it would otherwise cause confusion.
789
790 """
791 if system == 'Rhapsody':
792 # Apple's BSD derivative
793 # XXX How can we determine the marketing release number ?
794 return 'MacOS X Server',system+release,version
795
796 elif system == 'SunOS':
797 # Sun's OS
798 if release < '5':
799 # These releases use the old name SunOS
800 return system,release,version
801 # Modify release (marketing release = SunOS release - 3)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000802 l = release.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000803 if l:
804 try:
805 major = int(l[0])
806 except ValueError:
807 pass
808 else:
809 major = major - 3
810 l[0] = str(major)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000811 release = '.'.join(l)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000812 if release < '6':
813 system = 'Solaris'
814 else:
815 # XXX Whatever the new SunOS marketing name is...
816 system = 'Solaris'
817
818 elif system == 'IRIX64':
819 # IRIX reports IRIX64 on platforms with 64-bit support; yet it
820 # is really a version and not a different platform, since 32-bit
821 # apps are also supported..
822 system = 'IRIX'
823 if version:
824 version = version + ' (64bit)'
825 else:
826 version = '64bit'
827
828 elif system in ('win32','win16'):
829 # In case one of the other tricks
830 system = 'Windows'
831
832 return system,release,version
833
834### Various internal helpers
835
836def _platform(*args):
837
838 """ Helper to format the platform string in a filename
839 compatible format e.g. "system-version-machine".
840 """
841 # Format the platform string
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000842 platform = '-'.join(x.strip() for x in filter(len, args))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000843
844 # Cleanup some possible filename obstacles...
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000845 platform = platform.replace(' ','_')
846 platform = platform.replace('/','-')
847 platform = platform.replace('\\','-')
848 platform = platform.replace(':','-')
849 platform = platform.replace(';','-')
850 platform = platform.replace('"','-')
851 platform = platform.replace('(','-')
852 platform = platform.replace(')','-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000853
854 # No need to report 'unknown' information...
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000855 platform = platform.replace('unknown','')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000856
857 # Fold '--'s and remove trailing '-'
858 while 1:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000859 cleaned = platform.replace('--','-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000860 if cleaned == platform:
861 break
862 platform = cleaned
863 while platform[-1] == '-':
864 platform = platform[:-1]
865
866 return platform
867
868def _node(default=''):
869
870 """ Helper to determine the node name of this machine.
871 """
872 try:
873 import socket
874 except ImportError:
875 # No sockets...
876 return default
877 try:
878 return socket.gethostname()
879 except socket.error:
880 # Still not working...
881 return default
882
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000883def _follow_symlinks(filepath):
884
885 """ In case filepath is a symlink, follow it until a
886 real file is reached.
887 """
Georg Brandl673f7ef2008-01-05 21:20:19 +0000888 filepath = os.path.abspath(filepath)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000889 while os.path.islink(filepath):
890 filepath = os.path.normpath(
Hirokazu Yamamotob12716b2008-09-04 11:24:53 +0000891 os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000892 return filepath
893
894def _syscmd_uname(option,default=''):
895
896 """ Interface to the system's uname command.
897 """
898 if sys.platform in ('dos','win32','win16','os2'):
899 # XXX Others too ?
900 return default
901 try:
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000902 f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000903 except (AttributeError,os.error):
904 return default
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000905 output = f.read().strip()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000906 rc = f.close()
907 if not output or rc:
908 return default
909 else:
910 return output
911
912def _syscmd_file(target,default=''):
913
914 """ Interface to the system's file command.
915
916 The function uses the -b option of the file command to have it
Victor Stinnerddfb2c32010-08-13 16:30:15 +0000917 omit the filename in its output. Follow the symlinks. It returns
918 default in case the command should fail.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000919
920 """
Hirokazu Yamamotod26782e2008-09-01 14:35:47 +0000921 if sys.platform in ('dos','win32','win16','os2'):
922 # XXX Others too ?
923 return default
Victor Stinnerb27ee202010-04-18 18:28:09 +0000924 target = _follow_symlinks(target).replace('"', '\\"')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000925 try:
Victor Stinnerddfb2c32010-08-13 16:30:15 +0000926 f = os.popen('file -b "%s" 2> %s' % (target, DEV_NULL))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000927 except (AttributeError,os.error):
928 return default
Victor Stinnerb27ee202010-04-18 18:28:09 +0000929 output = f.read().strip()
930 rc = f.close()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000931 if not output or rc:
932 return default
933 else:
934 return output
935
936### Information about the used architecture
937
938# Default values for architecture; non-empty strings override the
939# defaults given as parameters
940_default_architecture = {
941 'win32': ('','WindowsPE'),
942 'win16': ('','Windows'),
943 'dos': ('','MSDOS'),
944}
945
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000946def architecture(executable=sys.executable,bits='',linkage=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000947
948 """ Queries the given executable (defaults to the Python interpreter
Brett Cannon8ab27df2003-08-05 03:52:04 +0000949 binary) for various architecture information.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000950
Brett Cannon8ab27df2003-08-05 03:52:04 +0000951 Returns a tuple (bits,linkage) which contains information about
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000952 the bit architecture and the linkage format used for the
953 executable. Both values are returned as strings.
954
955 Values that cannot be determined are returned as given by the
956 parameter presets. If bits is given as '', the sizeof(pointer)
957 (or sizeof(long) on Python version < 1.5.2) is used as
958 indicator for the supported pointer size.
959
960 The function relies on the system's "file" command to do the
961 actual work. This is available on most if not all Unix
Brett Cannon8ab27df2003-08-05 03:52:04 +0000962 platforms. On some non-Unix platforms where the "file" command
963 does not exist and the executable is set to the Python interpreter
964 binary defaults from _default_architecture are used.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000965
966 """
967 # Use the sizeof(pointer) as default number of bits if nothing
968 # else is given as default.
969 if not bits:
970 import struct
971 try:
972 size = struct.calcsize('P')
973 except struct.error:
974 # Older installations can only query longs
975 size = struct.calcsize('l')
976 bits = str(size*8) + 'bit'
Tim Peters0eadaac2003-04-24 16:02:54 +0000977
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000978 # Get data from the 'file' system command
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000979 if executable:
Victor Stinnerddfb2c32010-08-13 16:30:15 +0000980 fileout = _syscmd_file(executable, '')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000981 else:
Victor Stinnerddfb2c32010-08-13 16:30:15 +0000982 fileout = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000983
Victor Stinnerddfb2c32010-08-13 16:30:15 +0000984 if not fileout and \
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000985 executable == sys.executable:
986 # "file" command did not return anything; we'll try to provide
Tim Peters0eadaac2003-04-24 16:02:54 +0000987 # some sensible defaults then...
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000988 if sys.platform in _default_architecture:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000989 b,l = _default_architecture[sys.platform]
990 if b:
991 bits = b
992 if l:
993 linkage = l
994 return bits,linkage
995
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000996 if 'executable' not in fileout:
997 # Format not supported
998 return bits,linkage
999
1000 # Bits
1001 if '32-bit' in fileout:
1002 bits = '32bit'
1003 elif 'N32' in fileout:
1004 # On Irix only
1005 bits = 'n32bit'
1006 elif '64-bit' in fileout:
1007 bits = '64bit'
1008
1009 # Linkage
1010 if 'ELF' in fileout:
1011 linkage = 'ELF'
1012 elif 'PE' in fileout:
1013 # E.g. Windows uses this format
1014 if 'Windows' in fileout:
1015 linkage = 'WindowsPE'
1016 else:
1017 linkage = 'PE'
1018 elif 'COFF' in fileout:
1019 linkage = 'COFF'
1020 elif 'MS-DOS' in fileout:
1021 linkage = 'MSDOS'
1022 else:
1023 # XXX the A.OUT format also falls under this class...
1024 pass
1025
1026 return bits,linkage
1027
1028### Portable uname() interface
Tim Peters0eadaac2003-04-24 16:02:54 +00001029
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001030_uname_cache = None
1031
1032def uname():
1033
1034 """ Fairly portable uname interface. Returns a tuple
1035 of strings (system,node,release,version,machine,processor)
1036 identifying the underlying platform.
1037
1038 Note that unlike the os.uname function this also returns
Brett Cannon8ab27df2003-08-05 03:52:04 +00001039 possible processor information as an additional tuple entry.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001040
1041 Entries which cannot be determined are set to ''.
1042
1043 """
1044 global _uname_cache
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001045 no_os_uname = 0
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001046
1047 if _uname_cache is not None:
1048 return _uname_cache
1049
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001050 processor = ''
1051
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001052 # Get some infos from the builtin os.uname API...
1053 try:
1054 system,node,release,version,machine = os.uname()
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001055 except AttributeError:
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001056 no_os_uname = 1
1057
Georg Brandl62e2ca22010-07-31 21:54:24 +00001058 if no_os_uname or not list(filter(None, (system, node, release, version, machine))):
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001059 # Hmm, no there is either no uname or uname has returned
1060 #'unknowns'... we'll have to poke around the system then.
1061 if no_os_uname:
1062 system = sys.platform
1063 release = ''
1064 version = ''
1065 node = _node()
1066 machine = ''
1067
Amaury Forgeot d'Arc7a019842008-06-17 21:42:46 +00001068 use_syscmd_ver = 1
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001069
1070 # Try win32_ver() on win32 platforms
1071 if system == 'win32':
1072 release,version,csd,ptype = win32_ver()
1073 if release and version:
1074 use_syscmd_ver = 0
Christian Heimes02781dc2008-03-21 01:11:52 +00001075 # Try to use the PROCESSOR_* environment variables
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001076 # available on Win XP and later; see
1077 # http://support.microsoft.com/kb/888731 and
1078 # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001079 if not machine:
R. David Murrayca2edce2010-03-22 17:48:48 +00001080 # WOW64 processes mask the native architecture
1081 if "PROCESSOR_ARCHITEW6432" in os.environ:
1082 machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
1083 else:
1084 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001085 if not processor:
1086 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
Tim Peters0eadaac2003-04-24 16:02:54 +00001087
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001088 # Try the 'ver' system command available on some
1089 # platforms
1090 if use_syscmd_ver:
1091 system,release,version = _syscmd_ver(system)
Marc-André Lemburgcdc79232004-06-19 17:17:00 +00001092 # Normalize system to what win32_ver() normally returns
1093 # (_syscmd_ver() tends to return the vendor name as well)
1094 if system == 'Microsoft Windows':
1095 system = 'Windows'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001096 elif system == 'Microsoft' and release == 'Windows':
1097 # Under Windows Vista and Windows Server 2008,
1098 # Microsoft changed the output of the ver command. The
1099 # release is no longer printed. This causes the
1100 # system and release to be misidentified.
1101 system = 'Windows'
1102 if '6.0' == version[:3]:
1103 release = 'Vista'
1104 else:
1105 release = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001106
1107 # In case we still don't know anything useful, we'll try to
1108 # help ourselves
1109 if system in ('win32','win16'):
1110 if not version:
1111 if system == 'win32':
1112 version = '32bit'
1113 else:
1114 version = '16bit'
1115 system = 'Windows'
1116
1117 elif system[:4] == 'java':
1118 release,vendor,vminfo,osinfo = java_ver()
1119 system = 'Java'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001120 version = ', '.join(vminfo)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001121 if not version:
1122 version = vendor
1123
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001124 # System specific extensions
1125 if system == 'OpenVMS':
1126 # OpenVMS seems to have release and version mixed up
1127 if not release or release == '0':
1128 release = version
1129 version = ''
1130 # Get processor information
1131 try:
1132 import vms_lib
1133 except ImportError:
1134 pass
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001135 else:
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001136 csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
1137 if (cpu_number >= 128):
1138 processor = 'Alpha'
1139 else:
1140 processor = 'VAX'
1141 if not processor:
1142 # Get processor information from the uname system command
1143 processor = _syscmd_uname('-p','')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001144
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001145 #If any unknowns still exist, replace them with ''s, which are more portable
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001146 if system == 'unknown':
1147 system = ''
1148 if node == 'unknown':
1149 node = ''
1150 if release == 'unknown':
1151 release = ''
1152 if version == 'unknown':
1153 version = ''
1154 if machine == 'unknown':
1155 machine = ''
1156 if processor == 'unknown':
1157 processor = ''
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158
1159 # normalize name
1160 if system == 'Microsoft' and release == 'Windows':
1161 system = 'Windows'
1162 release = 'Vista'
1163
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001164 _uname_cache = system,node,release,version,machine,processor
1165 return _uname_cache
1166
1167### Direct interfaces to some of the uname() return values
1168
1169def system():
1170
1171 """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
1172
1173 An empty string is returned if the value cannot be determined.
1174
1175 """
1176 return uname()[0]
1177
1178def node():
1179
Brett Cannon8ab27df2003-08-05 03:52:04 +00001180 """ Returns the computer's network name (which may not be fully
1181 qualified)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001182
1183 An empty string is returned if the value cannot be determined.
1184
1185 """
1186 return uname()[1]
1187
1188def release():
1189
1190 """ Returns the system's release, e.g. '2.2.0' or 'NT'
1191
1192 An empty string is returned if the value cannot be determined.
1193
1194 """
1195 return uname()[2]
1196
1197def version():
1198
1199 """ Returns the system's release version, e.g. '#3 on degas'
1200
1201 An empty string is returned if the value cannot be determined.
1202
1203 """
1204 return uname()[3]
1205
1206def machine():
1207
1208 """ Returns the machine type, e.g. 'i386'
1209
1210 An empty string is returned if the value cannot be determined.
1211
1212 """
1213 return uname()[4]
1214
1215def processor():
1216
1217 """ Returns the (true) processor name, e.g. 'amdk6'
1218
1219 An empty string is returned if the value cannot be
1220 determined. Note that many platforms do not provide this
1221 information or simply return the same value as for machine(),
1222 e.g. NetBSD does this.
1223
1224 """
1225 return uname()[5]
1226
1227### Various APIs for extracting information from sys.version
1228
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001229_sys_version_parser = re.compile(
1230 r'([\w.+]+)\s*'
1231 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
Antoine Pitroufd036452008-08-19 17:56:33 +00001232 '\[([^\]]+)\]?', re.ASCII)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001233
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001234_ironpython_sys_version_parser = re.compile(
1235 r'IronPython\s*'
1236 '([\d\.]+)'
1237 '(?: \(([\d\.]+)\))?'
Antoine Pitroufd036452008-08-19 17:56:33 +00001238 ' on (.NET [\d\.]+)', re.ASCII)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001239
Benjamin Petersone549ead2009-03-28 21:42:05 +00001240_pypy_sys_version_parser = re.compile(
1241 r'([\w.+]+)\s*'
1242 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
1243 '\[PyPy [^\]]+\]?')
1244
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001245_sys_version_cache = {}
1246
1247def _sys_version(sys_version=None):
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001248
1249 """ Returns a parsed version of Python's sys.version as tuple
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001250 (name, version, branch, revision, buildno, builddate, compiler)
1251 referring to the Python implementation name, version, branch,
1252 revision, build number, build date/time as string and the compiler
1253 identification string.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001254
1255 Note that unlike the Python sys.version, the returned value
1256 for the Python version will always include the patchlevel (it
1257 defaults to '.0').
1258
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001259 The function returns empty strings for tuple entries that
1260 cannot be determined.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001261
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001262 sys_version may be given to parse an alternative version
1263 string, e.g. if the version was read from a different Python
1264 interpreter.
1265
1266 """
1267 # Get the Python version
1268 if sys_version is None:
1269 sys_version = sys.version
1270
1271 # Try the cache first
1272 result = _sys_version_cache.get(sys_version, None)
1273 if result is not None:
1274 return result
1275
1276 # Parse it
1277 if sys_version[:10] == 'IronPython':
1278 # IronPython
1279 name = 'IronPython'
1280 match = _ironpython_sys_version_parser.match(sys_version)
1281 if match is None:
1282 raise ValueError(
1283 'failed to parse IronPython sys.version: %s' %
1284 repr(sys_version))
1285 version, alt_version, compiler = match.groups()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001286 buildno = ''
1287 builddate = ''
1288
1289 elif sys.platform[:4] == 'java':
1290 # Jython
1291 name = 'Jython'
Benjamin Petersone549ead2009-03-28 21:42:05 +00001292 match = _sys_version_parser.match(sys_version)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001293 if match is None:
1294 raise ValueError(
1295 'failed to parse Jython sys.version: %s' %
1296 repr(sys_version))
Benjamin Petersone549ead2009-03-28 21:42:05 +00001297 version, buildno, builddate, buildtime, _ = match.groups()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001298 compiler = sys.platform
Benjamin Petersone549ead2009-03-28 21:42:05 +00001299
1300 elif "PyPy" in sys_version:
1301 # PyPy
1302 name = "PyPy"
1303 match = _pypy_sys_version_parser.match(sys_version)
1304 if match is None:
1305 raise ValueError("failed to parse PyPy sys.version: %s" %
1306 repr(sys_version))
1307 version, buildno, builddate, buildtime = match.groups()
1308 compiler = ""
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001309
1310 else:
1311 # CPython
1312 match = _sys_version_parser.match(sys_version)
1313 if match is None:
1314 raise ValueError(
1315 'failed to parse CPython sys.version: %s' %
1316 repr(sys_version))
1317 version, buildno, builddate, buildtime, compiler = \
1318 match.groups()
Benjamin Petersone549ead2009-03-28 21:42:05 +00001319 name = 'CPython'
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001320 builddate = builddate + ' ' + buildtime
1321
Georg Brandl82562422011-03-05 21:09:22 +01001322 if hasattr(sys, '_mercurial'):
1323 _, branch, revision = sys._mercurial
1324 elif hasattr(sys, 'subversion'):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001325 # sys.subversion was added in Python 2.5
1326 _, branch, revision = sys.subversion
1327 else:
1328 branch = ''
1329 revision = ''
1330
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001331 # Add the patchlevel version if missing
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001332 l = version.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001333 if len(l) == 2:
1334 l.append('0')
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001335 version = '.'.join(l)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001336
1337 # Build and cache the result
1338 result = (name, version, branch, revision, buildno, builddate, compiler)
1339 _sys_version_cache[sys_version] = result
1340 return result
1341
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001342def python_implementation():
1343
1344 """ Returns a string identifying the Python implementation.
1345
1346 Currently, the following implementations are identified:
Ezio Melottif16898b2011-05-04 18:37:50 +03001347 'CPython' (C implementation of Python),
1348 'IronPython' (.NET implementation of Python),
1349 'Jython' (Java implementation of Python),
1350 'PyPy' (Python implementation of Python).
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001351
1352 """
1353 return _sys_version()[0]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001354
1355def python_version():
1356
1357 """ Returns the Python version as string 'major.minor.patchlevel'
1358
1359 Note that unlike the Python sys.version, the returned value
1360 will always include the patchlevel (it defaults to 0).
1361
1362 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001363 return _sys_version()[1]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001364
1365def python_version_tuple():
1366
1367 """ Returns the Python version as tuple (major, minor, patchlevel)
1368 of strings.
1369
1370 Note that unlike the Python sys.version, the returned value
1371 will always include the patchlevel (it defaults to 0).
1372
1373 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001374 return tuple(_sys_version()[1].split('.'))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001375
1376def python_branch():
1377
1378 """ Returns a string identifying the Python implementation
1379 branch.
1380
1381 For CPython this is the Subversion branch from which the
1382 Python binary was built.
1383
1384 If not available, an empty string is returned.
1385
1386 """
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001387
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001388 return _sys_version()[2]
1389
1390def python_revision():
1391
1392 """ Returns a string identifying the Python implementation
1393 revision.
1394
1395 For CPython this is the Subversion revision from which the
1396 Python binary was built.
1397
1398 If not available, an empty string is returned.
1399
1400 """
1401 return _sys_version()[3]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001402
1403def python_build():
1404
1405 """ Returns a tuple (buildno, builddate) stating the Python
1406 build number and date as strings.
1407
1408 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001409 return _sys_version()[4:6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001410
1411def python_compiler():
1412
1413 """ Returns a string identifying the compiler used for compiling
1414 Python.
1415
1416 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001417 return _sys_version()[6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001418
1419### The Opus Magnum of platform strings :-)
1420
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001421_platform_cache = {}
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001422
1423def platform(aliased=0, terse=0):
1424
1425 """ Returns a single string identifying the underlying platform
1426 with as much useful information as possible (but no more :).
Tim Peters0eadaac2003-04-24 16:02:54 +00001427
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001428 The output is intended to be human readable rather than
1429 machine parseable. It may look different on different
1430 platforms and this is intended.
1431
1432 If "aliased" is true, the function will use aliases for
1433 various platforms that report system names which differ from
1434 their common names, e.g. SunOS will be reported as
1435 Solaris. The system_alias() function is used to implement
1436 this.
1437
1438 Setting terse to true causes the function to return only the
1439 absolute minimum information needed to identify the platform.
1440
1441 """
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001442 result = _platform_cache.get((aliased, terse), None)
1443 if result is not None:
1444 return result
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001445
1446 # Get uname information and then apply platform specific cosmetics
1447 # to it...
1448 system,node,release,version,machine,processor = uname()
1449 if machine == processor:
1450 processor = ''
1451 if aliased:
1452 system,release,version = system_alias(system,release,version)
1453
1454 if system == 'Windows':
1455 # MS platforms
1456 rel,vers,csd,ptype = win32_ver(version)
1457 if terse:
1458 platform = _platform(system,release)
1459 else:
1460 platform = _platform(system,release,version,csd)
1461
1462 elif system in ('Linux',):
1463 # Linux based systems
1464 distname,distversion,distid = dist('')
1465 if distname and not terse:
1466 platform = _platform(system,release,machine,processor,
1467 'with',
1468 distname,distversion,distid)
1469 else:
1470 # If the distribution name is unknown check for libc vs. glibc
1471 libcname,libcversion = libc_ver(sys.executable)
1472 platform = _platform(system,release,machine,processor,
1473 'with',
1474 libcname+libcversion)
1475 elif system == 'Java':
1476 # Java platforms
1477 r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001478 if terse or not os_name:
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001479 platform = _platform(system,release,version)
1480 else:
1481 platform = _platform(system,release,version,
1482 'on',
1483 os_name,os_version,os_arch)
1484
1485 elif system == 'MacOS':
1486 # MacOS platforms
1487 if terse:
1488 platform = _platform(system,release)
1489 else:
1490 platform = _platform(system,release,machine)
1491
1492 else:
1493 # Generic handler
1494 if terse:
1495 platform = _platform(system,release)
1496 else:
1497 bits,linkage = architecture(sys.executable)
1498 platform = _platform(system,release,machine,processor,bits,linkage)
Tim Peters0eadaac2003-04-24 16:02:54 +00001499
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001500 _platform_cache[(aliased, terse)] = platform
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001501 return platform
1502
1503### Command line interface
1504
1505if __name__ == '__main__':
1506 # Default is to print the aliased verbose platform string
Tim Peters0eadaac2003-04-24 16:02:54 +00001507 terse = ('terse' in sys.argv or '--terse' in sys.argv)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001508 aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001509 print(platform(aliased,terse))
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001510 sys.exit(0)