blob: eedc11c518d108f2e22cf962f0f6c857025553a6 [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
Jesus Ceafc990e92012-10-04 13:51:43 +0200114import sys, os, re, subprocess
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
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000133_libc_search = re.compile(r'(__libc_init)'
134 '|'
Tim Peters0eadaac2003-04-24 16:02:54 +0000135 '(GLIBC_([0-9.]+))'
136 '|'
Antoine Pitroufd036452008-08-19 17:56:33 +0000137 '(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
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000141 chunksize=2048):
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')
Walter Dörwaldc3b6ac72007-06-07 19:26:24 +0000162 binary = f.read(chunksize).decode('latin-1')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000163 pos = 0
164 while 1:
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000165 m = _libc_search.search(binary,pos)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000166 if not m:
Walter Dörwaldc3b6ac72007-06-07 19:26:24 +0000167 binary = f.read(chunksize).decode('latin-1')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000168 if not binary:
169 break
170 pos = 0
171 continue
172 libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
173 if libcinit and not lib:
174 lib = 'libc'
175 elif glibc:
176 if lib != 'glibc':
177 lib = 'glibc'
178 version = glibcversion
179 elif glibcversion > version:
180 version = glibcversion
181 elif so:
182 if lib != 'glibc':
183 lib = 'libc'
Victor Stinner87448812011-12-15 21:42:03 +0100184 if soversion and soversion > version:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000185 version = soversion
186 if threads and version[-len(threads):] != threads:
187 version = version + threads
188 pos = m.end()
189 f.close()
190 return lib,version
191
192def _dist_try_harder(distname,version,id):
193
Tim Peters0eadaac2003-04-24 16:02:54 +0000194 """ Tries some special tricks to get the distribution
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000195 information in case the default method fails.
196
197 Currently supports older SuSE Linux, Caldera OpenLinux and
198 Slackware Linux distributions.
199
200 """
201 if os.path.exists('/var/adm/inst-log/info'):
202 # SuSE Linux stores distribution information in that file
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000203 distname = 'SuSE'
Florent Xicluna7dde7922010-09-03 19:52:03 +0000204 for line in open('/var/adm/inst-log/info'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000205 tv = line.split()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000206 if len(tv) == 2:
207 tag,value = tv
208 else:
209 continue
210 if tag == 'MIN_DIST_VERSION':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000211 version = value.strip()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000212 elif tag == 'DIST_IDENT':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000213 values = value.split('-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000214 id = values[2]
215 return distname,version,id
216
217 if os.path.exists('/etc/.installed'):
218 # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
Florent Xicluna7dde7922010-09-03 19:52:03 +0000219 for line in open('/etc/.installed'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000220 pkg = line.split('-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000221 if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
222 # XXX does Caldera support non Intel platforms ? If yes,
223 # where can we find the needed id ?
224 return 'OpenLinux',pkg[1],id
225
226 if os.path.isdir('/usr/lib/setup'):
227 # Check for slackware verson tag file (thanks to Greg Andruk)
228 verfiles = os.listdir('/usr/lib/setup')
Guido van Rossum843c7342004-05-04 18:18:59 +0000229 for n in range(len(verfiles)-1, -1, -1):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000230 if verfiles[n][:14] != 'slack-version-':
231 del verfiles[n]
232 if verfiles:
233 verfiles.sort()
234 distname = 'slackware'
235 version = verfiles[-1][14:]
236 return distname,version,id
237
238 return distname,version,id
239
Antoine Pitroufd036452008-08-19 17:56:33 +0000240_release_filename = re.compile(r'(\w+)[-_](release|version)', re.ASCII)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000241_lsb_release_version = re.compile(r'(.+)'
242 ' release '
243 '([\d.]+)'
Antoine Pitroufd036452008-08-19 17:56:33 +0000244 '[^(]*(?:\((.+)\))?', re.ASCII)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000245_release_version = re.compile(r'([^0-9]+)'
246 '(?: release )?'
247 '([\d.]+)'
Antoine Pitroufd036452008-08-19 17:56:33 +0000248 '[^(]*(?:\((.+)\))?', re.ASCII)
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000249
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000250# See also http://www.novell.com/coolsolutions/feature/11251.html
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000251# and http://linuxmafia.com/faq/Admin/release-files.html
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000252# and http://data.linux-ntfs.org/rpm/whichrpm
253# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
Marc-André Lemburg380f4172005-11-07 16:11:02 +0000254
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000255_supported_dists = (
256 'SuSE', 'debian', 'fedora', 'redhat', 'centos',
257 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
258 'UnitedLinux', 'turbolinux')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000259
260def _parse_release_file(firstline):
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000261
Benjamin Peterson25001472010-01-25 03:37:42 +0000262 # Default to empty 'version' and 'id' strings. Both defaults are used
263 # when 'firstline' is empty. 'id' defaults to empty when an id can not
264 # be deduced.
265 version = ''
266 id = ''
267
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000268 # Parse the first line
269 m = _lsb_release_version.match(firstline)
270 if m is not None:
271 # LSB format: "distro release x.x (codename)"
272 return tuple(m.groups())
273
274 # Pre-LSB format: "distro x.x (codename)"
275 m = _release_version.match(firstline)
276 if m is not None:
277 return tuple(m.groups())
278
279 # Unkown format... take the first two words
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000280 l = firstline.strip().split()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000281 if l:
282 version = l[0]
283 if len(l) > 1:
284 id = l[1]
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000285 return '', version, id
286
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000287def linux_distribution(distname='', version='', id='',
288
289 supported_dists=_supported_dists,
290 full_distribution_name=1):
291
292 """ Tries to determine the name of the Linux OS distribution name.
293
294 The function first looks for a distribution release file in
295 /etc and then reverts to _dist_try_harder() in case no
296 suitable files are found.
297
298 supported_dists may be given to define the set of Linux
299 distributions to look for. It defaults to a list of currently
300 supported Linux distributions identified by their release file
301 name.
302
303 If full_distribution_name is true (default), the full
304 distribution read from the OS is returned. Otherwise the short
305 name taken from supported_dists is used.
306
307 Returns a tuple (distname,version,id) which default to the
308 args given as parameters.
309
310 """
311 try:
312 etc = os.listdir('/etc')
313 except os.error:
314 # Probably not a Unix system
315 return distname,version,id
316 etc.sort()
317 for file in etc:
318 m = _release_filename.match(file)
319 if m is not None:
320 _distname,dummy = m.groups()
321 if _distname in supported_dists:
322 distname = _distname
323 break
324 else:
325 return _dist_try_harder(distname,version,id)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000326
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000327 # Read the first line
Florent Xicluna7dde7922010-09-03 19:52:03 +0000328 with open('/etc/'+file, 'r') as f:
329 firstline = f.readline()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000330 _distname, _version, _id = _parse_release_file(firstline)
331
332 if _distname and full_distribution_name:
333 distname = _distname
334 if _version:
335 version = _version
336 if _id:
337 id = _id
338 return distname, version, id
339
340# To maintain backwards compatibility:
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000341
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000342def dist(distname='',version='',id='',
343
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000344 supported_dists=_supported_dists):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000345
Brett Cannon8ab27df2003-08-05 03:52:04 +0000346 """ Tries to determine the name of the Linux OS distribution name.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000347
348 The function first looks for a distribution release file in
349 /etc and then reverts to _dist_try_harder() in case no
350 suitable files are found.
351
Brett Cannon8ab27df2003-08-05 03:52:04 +0000352 Returns a tuple (distname,version,id) which default to the
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000353 args given as parameters.
354
355 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000356 return linux_distribution(distname, version, id,
357 supported_dists=supported_dists,
358 full_distribution_name=0)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000359
360class _popen:
361
362 """ Fairly portable (alternative) popen implementation.
363
364 This is mostly needed in case os.popen() is not available, or
365 doesn't work as advertised, e.g. in Win9X GUI programs like
366 PythonWin or IDLE.
367
368 Writing to the pipe is currently not supported.
369
370 """
371 tmpfile = ''
372 pipe = None
373 bufsize = None
374 mode = 'r'
375
376 def __init__(self,cmd,mode='r',bufsize=None):
377
378 if mode != 'r':
Collin Winterce36ad82007-08-30 01:19:48 +0000379 raise ValueError('popen()-emulation only supports read mode')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000380 import tempfile
381 self.tmpfile = tmpfile = tempfile.mktemp()
382 os.system(cmd + ' > %s' % tmpfile)
383 self.pipe = open(tmpfile,'rb')
384 self.bufsize = bufsize
385 self.mode = mode
386
387 def read(self):
388
389 return self.pipe.read()
390
391 def readlines(self):
392
393 if self.bufsize is not None:
394 return self.pipe.readlines()
395
396 def close(self,
397
398 remove=os.unlink,error=os.error):
399
400 if self.pipe:
401 rc = self.pipe.close()
402 else:
403 rc = 255
404 if self.tmpfile:
405 try:
406 remove(self.tmpfile)
407 except error:
408 pass
409 return rc
410
411 # Alias
412 __del__ = close
413
Antoine Pitrou877766d2011-03-19 17:00:37 +0100414def popen(cmd, mode='r', bufsize=-1):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000415
416 """ Portable popen() interface.
417 """
418 # Find a working popen implementation preferring win32pipe.popen
419 # over os.popen over _popen
420 popen = None
421 if os.environ.get('OS','') == 'Windows_NT':
422 # On NT win32pipe should work; on Win9x it hangs due to bugs
423 # in the MS C lib (see MS KnowledgeBase article Q150956)
424 try:
425 import win32pipe
426 except ImportError:
427 pass
428 else:
429 popen = win32pipe.popen
430 if popen is None:
431 if hasattr(os,'popen'):
432 popen = os.popen
433 # Check whether it works... it doesn't in GUI programs
434 # on Windows platforms
435 if sys.platform == 'win32': # XXX Others too ?
436 try:
437 popen('')
438 except os.error:
439 popen = _popen
440 else:
441 popen = _popen
442 if bufsize is None:
443 return popen(cmd,mode)
444 else:
445 return popen(cmd,mode,bufsize)
446
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000447def _norm_version(version, build=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000448
Brett Cannon8ab27df2003-08-05 03:52:04 +0000449 """ Normalize the version and build strings and return a single
Walter Dörwalde5a7fad2005-11-21 17:01:27 +0000450 version string using the format major.minor.build (or patchlevel).
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000451 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000452 l = version.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000453 if build:
454 l.append(build)
455 try:
456 ints = map(int,l)
457 except ValueError:
458 strings = l
459 else:
Neal Norwitz78a70bd2007-08-30 06:16:26 +0000460 strings = list(map(str,ints))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000461 version = '.'.join(strings[:3])
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000462 return version
463
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000464_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
465 '.*'
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000466 '\[.* ([\d.]+)\])')
467
468# Examples of VER command output:
469#
470# Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
471# Windows XP: Microsoft Windows XP [Version 5.1.2600]
472# Windows Vista: Microsoft Windows [Version 6.0.6002]
473#
474# Note that the "Version" string gets localized on different
475# Windows versions.
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000476
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000477def _syscmd_ver(system='', release='', version='',
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000478
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000479 supported_platforms=('win32','win16','dos','os2')):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000480
481 """ Tries to figure out the OS version used and returns
482 a tuple (system,release,version).
Tim Peters0eadaac2003-04-24 16:02:54 +0000483
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000484 It uses the "ver" shell command for this which is known
485 to exists on Windows, DOS and OS/2. XXX Others too ?
486
487 In case this fails, the given parameters are used as
488 defaults.
489
490 """
491 if sys.platform not in supported_platforms:
492 return system,release,version
493
494 # Try some common cmd strings
495 for cmd in ('ver','command /c ver','cmd /c ver'):
496 try:
497 pipe = popen(cmd)
498 info = pipe.read()
499 if pipe.close():
Collin Winterce36ad82007-08-30 01:19:48 +0000500 raise os.error('command failed')
Ezio Melotti13925002011-03-16 11:05:33 +0200501 # XXX How can I suppress shell errors from being written
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000502 # to stderr ?
Guido van Rossumb940e112007-01-10 16:19:56 +0000503 except os.error as why:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000504 #print 'Command %s failed: %s' % (cmd,why)
505 continue
Guido van Rossumb940e112007-01-10 16:19:56 +0000506 except IOError as why:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000507 #print 'Command %s failed: %s' % (cmd,why)
508 continue
509 else:
510 break
511 else:
512 return system,release,version
513
514 # Parse the output
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000515 info = info.strip()
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +0000516 m = _ver_output.match(info)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000517 if m is not None:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000518 system,release,version = m.groups()
519 # Strip trailing dots from version and release
520 if release[-1] == '.':
521 release = release[:-1]
522 if version[-1] == '.':
523 version = version[:-1]
524 # Normalize the version and build strings (eliminating additional
525 # zeros)
526 version = _norm_version(version)
527 return system,release,version
528
529def _win32_getvalue(key,name,default=''):
530
531 """ Read a value for name from the registry key.
532
533 In case this fails, default is returned.
534
535 """
Christian Heimes02781dc2008-03-21 01:11:52 +0000536 try:
537 # Use win32api if available
538 from win32api import RegQueryValueEx
539 except ImportError:
Georg Brandl38feaf02008-05-25 07:45:51 +0000540 # On Python 2.0 and later, emulate using winreg
541 import winreg
542 RegQueryValueEx = winreg.QueryValueEx
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000543 try:
544 return RegQueryValueEx(key,name)
545 except:
546 return default
547
548def win32_ver(release='',version='',csd='',ptype=''):
549
550 """ Get additional version information from the Windows Registry
551 and return a tuple (version,csd,ptype) referring to version
Brian Curtin10dda6e2012-02-01 15:14:00 -0600552 number, CSD level (service pack), and OS type (multi/single
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000553 processor).
554
555 As a hint: ptype returns 'Uniprocessor Free' on single
556 processor NT machines and 'Multiprocessor Free' on multi
557 processor machines. The 'Free' refers to the OS version being
558 free of debugging code. It could also state 'Checked' which
559 means the OS version uses debugging code, i.e. code that
560 checks arguments, ranges, etc. (Thomas Heller).
561
Christian Heimes02781dc2008-03-21 01:11:52 +0000562 Note: this function works best with Mark Hammond's win32
563 package installed, but also on Python 2.3 and later. It
564 obviously only runs on Win32 compatible platforms.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000565
566 """
567 # XXX Is there any way to find out the processor type on WinXX ?
568 # XXX Is win32 available on Windows CE ?
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000569 #
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000570 # Adapted from code posted by Karl Putland to comp.lang.python.
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000571 #
572 # The mappings between reg. values and release names can be found
573 # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000574
575 # Import the needed APIs
576 try:
577 import win32api
Christian Heimes02781dc2008-03-21 01:11:52 +0000578 from win32api import RegQueryValueEx, RegOpenKeyEx, \
579 RegCloseKey, GetVersionEx
580 from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
581 VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000582 except ImportError:
Christian Heimes02781dc2008-03-21 01:11:52 +0000583 # Emulate the win32api module using Python APIs
584 try:
585 sys.getwindowsversion
586 except AttributeError:
587 # No emulation possible, so return the defaults...
588 return release,version,csd,ptype
589 else:
Georg Brandl38feaf02008-05-25 07:45:51 +0000590 # Emulation using winreg (added in Python 2.0) and
Christian Heimes02781dc2008-03-21 01:11:52 +0000591 # sys.getwindowsversion() (added in Python 2.3)
Georg Brandl38feaf02008-05-25 07:45:51 +0000592 import winreg
Christian Heimes02781dc2008-03-21 01:11:52 +0000593 GetVersionEx = sys.getwindowsversion
Georg Brandl38feaf02008-05-25 07:45:51 +0000594 RegQueryValueEx = winreg.QueryValueEx
595 RegOpenKeyEx = winreg.OpenKeyEx
596 RegCloseKey = winreg.CloseKey
597 HKEY_LOCAL_MACHINE = winreg.HKEY_LOCAL_MACHINE
Christian Heimes02781dc2008-03-21 01:11:52 +0000598 VER_PLATFORM_WIN32_WINDOWS = 1
599 VER_PLATFORM_WIN32_NT = 2
600 VER_NT_WORKSTATION = 1
Brian Curtin6e2824d2010-05-06 03:05:50 +0000601 VER_NT_SERVER = 3
602 REG_SZ = 1
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000603
604 # Find out the registry key and some general version infos
Brian Curtin6e2824d2010-05-06 03:05:50 +0000605 winver = GetVersionEx()
606 maj,min,buildno,plat,csd = winver
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000607 version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
Brian Curtin6e2824d2010-05-06 03:05:50 +0000608 if hasattr(winver, "service_pack"):
609 if winver.service_pack != "":
610 csd = 'SP%s' % winver.service_pack_major
611 else:
612 if csd[:13] == 'Service Pack ':
613 csd = 'SP' + csd[13:]
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000614
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000615 if plat == VER_PLATFORM_WIN32_WINDOWS:
616 regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
617 # Try to guess the release name
618 if maj == 4:
619 if min == 0:
620 release = '95'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000621 elif min == 10:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000622 release = '98'
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000623 elif min == 90:
624 release = 'Me'
625 else:
626 release = 'postMe'
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000627 elif maj == 5:
628 release = '2000'
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000629
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000630 elif plat == VER_PLATFORM_WIN32_NT:
631 regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
632 if maj <= 4:
633 release = 'NT'
634 elif maj == 5:
Marc-André Lemburg91e83e22004-03-25 18:35:12 +0000635 if min == 0:
636 release = '2000'
637 elif min == 1:
638 release = 'XP'
639 elif min == 2:
640 release = '2003Server'
641 else:
642 release = 'post2003'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000643 elif maj == 6:
Brian Curtin6e2824d2010-05-06 03:05:50 +0000644 if hasattr(winver, "product_type"):
645 product_type = winver.product_type
646 else:
647 product_type = VER_NT_WORKSTATION
648 # Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
649 # or help from the registry, we cannot properly identify
650 # non-workstation versions.
Christian Heimes02781dc2008-03-21 01:11:52 +0000651 try:
Brian Curtin6e2824d2010-05-06 03:05:50 +0000652 key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
653 name, type = RegQueryValueEx(key, "ProductName")
654 # Discard any type that isn't REG_SZ
655 if type == REG_SZ and name.find("Server") != -1:
656 product_type = VER_NT_SERVER
657 except WindowsError:
658 # Use default of VER_NT_WORKSTATION
659 pass
660
661 if min == 0:
662 if product_type == VER_NT_WORKSTATION:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000663 release = 'Vista'
664 else:
Brian Curtin6e2824d2010-05-06 03:05:50 +0000665 release = '2008Server'
666 elif min == 1:
667 if product_type == VER_NT_WORKSTATION:
668 release = '7'
669 else:
670 release = '2008ServerR2'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000671 else:
672 release = 'post2008Server'
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000673
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000674 else:
675 if not release:
676 # E.g. Win3.1 with win32s
677 release = '%i.%i' % (maj,min)
678 return release,version,csd,ptype
679
680 # Open the registry key
681 try:
Christian Heimes02781dc2008-03-21 01:11:52 +0000682 keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000683 # Get a value to make sure the key exists...
Christian Heimes02781dc2008-03-21 01:11:52 +0000684 RegQueryValueEx(keyCurVer, 'SystemRoot')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000685 except:
686 return release,version,csd,ptype
Tim Peters0eadaac2003-04-24 16:02:54 +0000687
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000688 # Parse values
689 #subversion = _win32_getvalue(keyCurVer,
690 # 'SubVersionNumber',
691 # ('',1))[0]
692 #if subversion:
693 # release = release + subversion # 95a, 95b, etc.
694 build = _win32_getvalue(keyCurVer,
695 'CurrentBuildNumber',
696 ('',1))[0]
697 ptype = _win32_getvalue(keyCurVer,
698 'CurrentType',
699 (ptype,1))[0]
700
701 # Normalize version
702 version = _norm_version(version,build)
703
704 # Close key
705 RegCloseKey(keyCurVer)
706 return release,version,csd,ptype
707
708def _mac_ver_lookup(selectors,default=None):
709
Benjamin Petersonebacd262008-05-29 21:09:51 +0000710 from _gestalt import gestalt
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000711 l = []
712 append = l.append
713 for selector in selectors:
714 try:
715 append(gestalt(selector))
Benjamin Petersonebacd262008-05-29 21:09:51 +0000716 except (RuntimeError, OSError):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000717 append(default)
718 return l
719
720def _bcd2str(bcd):
721
722 return hex(bcd)[2:]
723
Ronald Oussorene186e382010-07-23 11:54:59 +0000724def _mac_ver_gestalt():
725 """
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000726 Thanks to Mark R. Levinson for mailing documentation links and
727 code examples for this function. Documentation for the
728 gestalt() API is available online at:
729
730 http://www.rgaros.nl/gestalt/
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000731 """
732 # Check whether the version info module is available
733 try:
Benjamin Petersonebacd262008-05-29 21:09:51 +0000734 import _gestalt
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000735 except ImportError:
Ronald Oussorene186e382010-07-23 11:54:59 +0000736 return None
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000737 # Get the infos
Ronald Oussoren19258d52010-02-07 11:33:33 +0000738 sysv, sysa = _mac_ver_lookup(('sysv','sysa'))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000739 # Decode the infos
740 if sysv:
741 major = (sysv & 0xFF00) >> 8
742 minor = (sysv & 0x00F0) >> 4
743 patch = (sysv & 0x000F)
Christian Heimese4ca8152008-05-08 17:18:53 +0000744
745 if (major, minor) >= (10, 4):
746 # the 'sysv' gestald cannot return patchlevels
747 # higher than 9. Apple introduced 3 new
748 # gestalt codes in 10.4 to deal with this
749 # issue (needed because patch levels can
750 # run higher than 9, such as 10.4.11)
751 major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
752 release = '%i.%i.%i' %(major, minor, patch)
753 else:
754 release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
Benjamin Peterson856ff5f2008-05-29 21:22:40 +0000755
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000756 if sysa:
Tim Peters0eadaac2003-04-24 16:02:54 +0000757 machine = {0x1: '68k',
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758 0x2: 'PowerPC',
759 0xa: 'i386'}.get(sysa,'')
Ronald Oussorene186e382010-07-23 11:54:59 +0000760
Ned Deily58e33502011-07-13 15:07:04 -0700761 versioninfo=('', '', '')
Ronald Oussorene186e382010-07-23 11:54:59 +0000762 return release,versioninfo,machine
763
764def _mac_ver_xml():
765 fn = '/System/Library/CoreServices/SystemVersion.plist'
766 if not os.path.exists(fn):
767 return None
768
769 try:
770 import plistlib
771 except ImportError:
772 return None
773
774 pl = plistlib.readPlist(fn)
775 release = pl['ProductVersion']
776 versioninfo=('', '', '')
777 machine = os.uname()[4]
Ronald Oussorenfcd77012010-08-03 07:42:42 +0000778 if machine in ('ppc', 'Power Macintosh'):
Ronald Oussorene186e382010-07-23 11:54:59 +0000779 # for compatibility with the gestalt based code
780 machine = 'PowerPC'
781
782 return release,versioninfo,machine
783
784
785def mac_ver(release='',versioninfo=('','',''),machine=''):
786
787 """ Get MacOS version information and return it as tuple (release,
788 versioninfo, machine) with versioninfo being a tuple (version,
789 dev_stage, non_release_version).
790
791 Entries which cannot be determined are set to the paramter values
792 which default to ''. All tuple entries are strings.
793 """
794
795 # First try reading the information from an XML file which should
796 # always be present
797 info = _mac_ver_xml()
798 if info is not None:
799 return info
800
801 # If that doesn't work for some reason fall back to reading the
802 # information using gestalt calls.
803 info = _mac_ver_gestalt()
804 if info is not None:
805 return info
806
807 # If that also doesn't work return the default values
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000808 return release,versioninfo,machine
809
Neal Norwitz9b924c62003-06-29 04:17:45 +0000810def _java_getprop(name,default):
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000811
812 from java.lang import System
813 try:
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000814 value = System.getProperty(name)
815 if value is None:
816 return default
817 return value
818 except AttributeError:
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000819 return default
820
821def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
Tim Peters0eadaac2003-04-24 16:02:54 +0000822
Brett Cannon8ab27df2003-08-05 03:52:04 +0000823 """ Version interface for Jython.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000824
825 Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
826 a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
827 tuple (os_name,os_version,os_arch).
828
829 Values which cannot be determined are set to the defaults
830 given as parameters (which all default to '').
831
832 """
833 # Import the needed APIs
834 try:
835 import java.lang
836 except ImportError:
837 return release,vendor,vminfo,osinfo
838
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000839 vendor = _java_getprop('java.vendor', vendor)
840 release = _java_getprop('java.version', release)
841 vm_name, vm_release, vm_vendor = vminfo
842 vm_name = _java_getprop('java.vm.name', vm_name)
843 vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
844 vm_release = _java_getprop('java.vm.version', vm_release)
845 vminfo = vm_name, vm_release, vm_vendor
846 os_name, os_version, os_arch = osinfo
847 os_arch = _java_getprop('java.os.arch', os_arch)
848 os_name = _java_getprop('java.os.name', os_name)
849 os_version = _java_getprop('java.os.version', os_version)
850 osinfo = os_name, os_version, os_arch
Tim Peters0eadaac2003-04-24 16:02:54 +0000851
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000852 return release, vendor, vminfo, osinfo
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000853
854### System name aliasing
855
856def system_alias(system,release,version):
857
858 """ Returns (system,release,version) aliased to common
859 marketing names used for some systems.
860
861 It also does some reordering of the information in some cases
862 where it would otherwise cause confusion.
863
864 """
865 if system == 'Rhapsody':
866 # Apple's BSD derivative
867 # XXX How can we determine the marketing release number ?
868 return 'MacOS X Server',system+release,version
869
870 elif system == 'SunOS':
871 # Sun's OS
872 if release < '5':
873 # These releases use the old name SunOS
874 return system,release,version
875 # Modify release (marketing release = SunOS release - 3)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000876 l = release.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000877 if l:
878 try:
879 major = int(l[0])
880 except ValueError:
881 pass
882 else:
883 major = major - 3
884 l[0] = str(major)
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000885 release = '.'.join(l)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000886 if release < '6':
887 system = 'Solaris'
888 else:
889 # XXX Whatever the new SunOS marketing name is...
890 system = 'Solaris'
891
892 elif system == 'IRIX64':
893 # IRIX reports IRIX64 on platforms with 64-bit support; yet it
894 # is really a version and not a different platform, since 32-bit
895 # apps are also supported..
896 system = 'IRIX'
897 if version:
898 version = version + ' (64bit)'
899 else:
900 version = '64bit'
901
902 elif system in ('win32','win16'):
903 # In case one of the other tricks
904 system = 'Windows'
905
906 return system,release,version
907
908### Various internal helpers
909
910def _platform(*args):
911
912 """ Helper to format the platform string in a filename
913 compatible format e.g. "system-version-machine".
914 """
915 # Format the platform string
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000916 platform = '-'.join(x.strip() for x in filter(len, args))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000917
918 # Cleanup some possible filename obstacles...
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000919 platform = platform.replace(' ','_')
920 platform = platform.replace('/','-')
921 platform = platform.replace('\\','-')
922 platform = platform.replace(':','-')
923 platform = platform.replace(';','-')
924 platform = platform.replace('"','-')
925 platform = platform.replace('(','-')
926 platform = platform.replace(')','-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000927
928 # No need to report 'unknown' information...
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000929 platform = platform.replace('unknown','')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000930
931 # Fold '--'s and remove trailing '-'
932 while 1:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000933 cleaned = platform.replace('--','-')
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000934 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
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000957def _follow_symlinks(filepath):
958
959 """ In case filepath is a symlink, follow it until a
960 real file is reached.
961 """
Georg Brandl673f7ef2008-01-05 21:20:19 +0000962 filepath = os.path.abspath(filepath)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000963 while os.path.islink(filepath):
964 filepath = os.path.normpath(
Hirokazu Yamamotob12716b2008-09-04 11:24:53 +0000965 os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000966 return filepath
967
968def _syscmd_uname(option,default=''):
969
970 """ Interface to the system's uname command.
971 """
972 if sys.platform in ('dos','win32','win16','os2'):
973 # XXX Others too ?
974 return default
975 try:
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000976 f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000977 except (AttributeError,os.error):
978 return default
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000979 output = f.read().strip()
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000980 rc = f.close()
981 if not output or rc:
982 return default
983 else:
984 return output
985
986def _syscmd_file(target,default=''):
987
988 """ Interface to the system's file command.
989
990 The function uses the -b option of the file command to have it
Victor Stinnerddfb2c32010-08-13 16:30:15 +0000991 omit the filename in its output. Follow the symlinks. It returns
992 default in case the command should fail.
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000993
994 """
Hirokazu Yamamotod26782e2008-09-01 14:35:47 +0000995 if sys.platform in ('dos','win32','win16','os2'):
996 # XXX Others too ?
997 return default
Jesus Ceafc990e92012-10-04 13:51:43 +0200998 target = _follow_symlinks(target)
Marc-André Lemburg246d8472003-04-24 11:36:11 +0000999 try:
Jesus Cea685fffa2012-10-05 05:21:42 +02001000 proc = subprocess.Popen(['file', target],
1001 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001002 except (AttributeError,os.error):
1003 return default
Jesus Ceaadc82112012-10-05 04:58:38 +02001004 output = proc.communicate()[0].decode("latin-1")
Jesus Ceafc990e92012-10-04 13:51:43 +02001005 rc = proc.wait()
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001006 if not output or rc:
1007 return default
1008 else:
1009 return output
1010
1011### Information about the used architecture
1012
1013# Default values for architecture; non-empty strings override the
1014# defaults given as parameters
1015_default_architecture = {
1016 'win32': ('','WindowsPE'),
1017 'win16': ('','Windows'),
1018 'dos': ('','MSDOS'),
1019}
1020
Marc-André Lemburg366a0fe2003-04-24 11:46:35 +00001021def architecture(executable=sys.executable,bits='',linkage=''):
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001022
1023 """ Queries the given executable (defaults to the Python interpreter
Brett Cannon8ab27df2003-08-05 03:52:04 +00001024 binary) for various architecture information.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001025
Brett Cannon8ab27df2003-08-05 03:52:04 +00001026 Returns a tuple (bits,linkage) which contains information about
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001027 the bit architecture and the linkage format used for the
1028 executable. Both values are returned as strings.
1029
1030 Values that cannot be determined are returned as given by the
1031 parameter presets. If bits is given as '', the sizeof(pointer)
1032 (or sizeof(long) on Python version < 1.5.2) is used as
1033 indicator for the supported pointer size.
1034
1035 The function relies on the system's "file" command to do the
1036 actual work. This is available on most if not all Unix
Brett Cannon8ab27df2003-08-05 03:52:04 +00001037 platforms. On some non-Unix platforms where the "file" command
1038 does not exist and the executable is set to the Python interpreter
1039 binary defaults from _default_architecture are used.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001040
1041 """
1042 # Use the sizeof(pointer) as default number of bits if nothing
1043 # else is given as default.
1044 if not bits:
1045 import struct
1046 try:
1047 size = struct.calcsize('P')
1048 except struct.error:
1049 # Older installations can only query longs
1050 size = struct.calcsize('l')
1051 bits = str(size*8) + 'bit'
Tim Peters0eadaac2003-04-24 16:02:54 +00001052
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001053 # Get data from the 'file' system command
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001054 if executable:
Victor Stinnerddfb2c32010-08-13 16:30:15 +00001055 fileout = _syscmd_file(executable, '')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001056 else:
Victor Stinnerddfb2c32010-08-13 16:30:15 +00001057 fileout = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001058
Victor Stinnerddfb2c32010-08-13 16:30:15 +00001059 if not fileout and \
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001060 executable == sys.executable:
1061 # "file" command did not return anything; we'll try to provide
Tim Peters0eadaac2003-04-24 16:02:54 +00001062 # some sensible defaults then...
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001063 if sys.platform in _default_architecture:
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001064 b,l = _default_architecture[sys.platform]
1065 if b:
1066 bits = b
1067 if l:
1068 linkage = l
1069 return bits,linkage
1070
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001071 if 'executable' not in fileout:
1072 # Format not supported
1073 return bits,linkage
1074
1075 # Bits
1076 if '32-bit' in fileout:
1077 bits = '32bit'
1078 elif 'N32' in fileout:
1079 # On Irix only
1080 bits = 'n32bit'
1081 elif '64-bit' in fileout:
1082 bits = '64bit'
1083
1084 # Linkage
1085 if 'ELF' in fileout:
1086 linkage = 'ELF'
1087 elif 'PE' in fileout:
1088 # E.g. Windows uses this format
1089 if 'Windows' in fileout:
1090 linkage = 'WindowsPE'
1091 else:
1092 linkage = 'PE'
1093 elif 'COFF' in fileout:
1094 linkage = 'COFF'
1095 elif 'MS-DOS' in fileout:
1096 linkage = 'MSDOS'
1097 else:
1098 # XXX the A.OUT format also falls under this class...
1099 pass
1100
1101 return bits,linkage
1102
1103### Portable uname() interface
Tim Peters0eadaac2003-04-24 16:02:54 +00001104
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001105_uname_cache = None
1106
1107def uname():
1108
1109 """ Fairly portable uname interface. Returns a tuple
1110 of strings (system,node,release,version,machine,processor)
1111 identifying the underlying platform.
1112
1113 Note that unlike the os.uname function this also returns
Brett Cannon8ab27df2003-08-05 03:52:04 +00001114 possible processor information as an additional tuple entry.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001115
1116 Entries which cannot be determined are set to ''.
1117
1118 """
1119 global _uname_cache
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001120 no_os_uname = 0
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001121
1122 if _uname_cache is not None:
1123 return _uname_cache
1124
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001125 processor = ''
1126
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001127 # Get some infos from the builtin os.uname API...
1128 try:
1129 system,node,release,version,machine = os.uname()
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001130 except AttributeError:
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001131 no_os_uname = 1
1132
Georg Brandl62e2ca22010-07-31 21:54:24 +00001133 if no_os_uname or not list(filter(None, (system, node, release, version, machine))):
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001134 # Hmm, no there is either no uname or uname has returned
1135 #'unknowns'... we'll have to poke around the system then.
1136 if no_os_uname:
1137 system = sys.platform
1138 release = ''
1139 version = ''
1140 node = _node()
1141 machine = ''
1142
Amaury Forgeot d'Arc7a019842008-06-17 21:42:46 +00001143 use_syscmd_ver = 1
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001144
1145 # Try win32_ver() on win32 platforms
1146 if system == 'win32':
1147 release,version,csd,ptype = win32_ver()
1148 if release and version:
1149 use_syscmd_ver = 0
Christian Heimes02781dc2008-03-21 01:11:52 +00001150 # Try to use the PROCESSOR_* environment variables
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001151 # available on Win XP and later; see
1152 # http://support.microsoft.com/kb/888731 and
1153 # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001154 if not machine:
R. David Murrayca2edce2010-03-22 17:48:48 +00001155 # WOW64 processes mask the native architecture
1156 if "PROCESSOR_ARCHITEW6432" in os.environ:
1157 machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
1158 else:
1159 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001160 if not processor:
1161 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
Tim Peters0eadaac2003-04-24 16:02:54 +00001162
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001163 # Try the 'ver' system command available on some
1164 # platforms
1165 if use_syscmd_ver:
1166 system,release,version = _syscmd_ver(system)
Marc-André Lemburgcdc79232004-06-19 17:17:00 +00001167 # Normalize system to what win32_ver() normally returns
1168 # (_syscmd_ver() tends to return the vendor name as well)
1169 if system == 'Microsoft Windows':
1170 system = 'Windows'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001171 elif system == 'Microsoft' and release == 'Windows':
1172 # Under Windows Vista and Windows Server 2008,
1173 # Microsoft changed the output of the ver command. The
1174 # release is no longer printed. This causes the
1175 # system and release to be misidentified.
1176 system = 'Windows'
1177 if '6.0' == version[:3]:
1178 release = 'Vista'
1179 else:
1180 release = ''
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001181
1182 # In case we still don't know anything useful, we'll try to
1183 # help ourselves
1184 if system in ('win32','win16'):
1185 if not version:
1186 if system == 'win32':
1187 version = '32bit'
1188 else:
1189 version = '16bit'
1190 system = 'Windows'
1191
1192 elif system[:4] == 'java':
1193 release,vendor,vminfo,osinfo = java_ver()
1194 system = 'Java'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001195 version = ', '.join(vminfo)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001196 if not version:
1197 version = vendor
1198
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001199 # System specific extensions
1200 if system == 'OpenVMS':
1201 # OpenVMS seems to have release and version mixed up
1202 if not release or release == '0':
1203 release = version
1204 version = ''
1205 # Get processor information
1206 try:
1207 import vms_lib
1208 except ImportError:
1209 pass
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001210 else:
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001211 csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
1212 if (cpu_number >= 128):
1213 processor = 'Alpha'
1214 else:
1215 processor = 'VAX'
1216 if not processor:
1217 # Get processor information from the uname system command
1218 processor = _syscmd_uname('-p','')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001219
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001220 #If any unknowns still exist, replace them with ''s, which are more portable
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001221 if system == 'unknown':
1222 system = ''
1223 if node == 'unknown':
1224 node = ''
1225 if release == 'unknown':
1226 release = ''
1227 if version == 'unknown':
1228 version = ''
1229 if machine == 'unknown':
1230 machine = ''
1231 if processor == 'unknown':
1232 processor = ''
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001233
1234 # normalize name
1235 if system == 'Microsoft' and release == 'Windows':
1236 system = 'Windows'
1237 release = 'Vista'
1238
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001239 _uname_cache = system,node,release,version,machine,processor
1240 return _uname_cache
1241
1242### Direct interfaces to some of the uname() return values
1243
1244def system():
1245
1246 """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
1247
1248 An empty string is returned if the value cannot be determined.
1249
1250 """
1251 return uname()[0]
1252
1253def node():
1254
Brett Cannon8ab27df2003-08-05 03:52:04 +00001255 """ Returns the computer's network name (which may not be fully
1256 qualified)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001257
1258 An empty string is returned if the value cannot be determined.
1259
1260 """
1261 return uname()[1]
1262
1263def release():
1264
1265 """ Returns the system's release, e.g. '2.2.0' or 'NT'
1266
1267 An empty string is returned if the value cannot be determined.
1268
1269 """
1270 return uname()[2]
1271
1272def version():
1273
1274 """ Returns the system's release version, e.g. '#3 on degas'
1275
1276 An empty string is returned if the value cannot be determined.
1277
1278 """
1279 return uname()[3]
1280
1281def machine():
1282
1283 """ Returns the machine type, e.g. 'i386'
1284
1285 An empty string is returned if the value cannot be determined.
1286
1287 """
1288 return uname()[4]
1289
1290def processor():
1291
1292 """ Returns the (true) processor name, e.g. 'amdk6'
1293
1294 An empty string is returned if the value cannot be
1295 determined. Note that many platforms do not provide this
1296 information or simply return the same value as for machine(),
1297 e.g. NetBSD does this.
1298
1299 """
1300 return uname()[5]
1301
1302### Various APIs for extracting information from sys.version
1303
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001304_sys_version_parser = re.compile(
1305 r'([\w.+]+)\s*'
1306 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
Antoine Pitroufd036452008-08-19 17:56:33 +00001307 '\[([^\]]+)\]?', re.ASCII)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001308
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001309_ironpython_sys_version_parser = re.compile(
1310 r'IronPython\s*'
1311 '([\d\.]+)'
1312 '(?: \(([\d\.]+)\))?'
Antoine Pitroufd036452008-08-19 17:56:33 +00001313 ' on (.NET [\d\.]+)', re.ASCII)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001314
Benjamin Petersone549ead2009-03-28 21:42:05 +00001315_pypy_sys_version_parser = re.compile(
1316 r'([\w.+]+)\s*'
1317 '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
1318 '\[PyPy [^\]]+\]?')
1319
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001320_sys_version_cache = {}
1321
1322def _sys_version(sys_version=None):
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001323
1324 """ Returns a parsed version of Python's sys.version as tuple
Benjamin Peterson5f28b7b2009-03-26 21:49:58 +00001325 (name, version, branch, revision, buildno, builddate, compiler)
1326 referring to the Python implementation name, version, branch,
1327 revision, build number, build date/time as string and the compiler
1328 identification string.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001329
1330 Note that unlike the Python sys.version, the returned value
1331 for the Python version will always include the patchlevel (it
1332 defaults to '.0').
1333
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001334 The function returns empty strings for tuple entries that
1335 cannot be determined.
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001336
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001337 sys_version may be given to parse an alternative version
1338 string, e.g. if the version was read from a different Python
1339 interpreter.
1340
1341 """
1342 # Get the Python version
1343 if sys_version is None:
1344 sys_version = sys.version
1345
1346 # Try the cache first
1347 result = _sys_version_cache.get(sys_version, None)
1348 if result is not None:
1349 return result
1350
1351 # Parse it
1352 if sys_version[:10] == 'IronPython':
1353 # IronPython
1354 name = 'IronPython'
1355 match = _ironpython_sys_version_parser.match(sys_version)
1356 if match is None:
1357 raise ValueError(
1358 'failed to parse IronPython sys.version: %s' %
1359 repr(sys_version))
1360 version, alt_version, compiler = match.groups()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001361 buildno = ''
1362 builddate = ''
1363
1364 elif sys.platform[:4] == 'java':
1365 # Jython
1366 name = 'Jython'
Benjamin Petersone549ead2009-03-28 21:42:05 +00001367 match = _sys_version_parser.match(sys_version)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001368 if match is None:
1369 raise ValueError(
1370 'failed to parse Jython sys.version: %s' %
1371 repr(sys_version))
Benjamin Petersone549ead2009-03-28 21:42:05 +00001372 version, buildno, builddate, buildtime, _ = match.groups()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001373 compiler = sys.platform
Benjamin Petersone549ead2009-03-28 21:42:05 +00001374
1375 elif "PyPy" in sys_version:
1376 # PyPy
1377 name = "PyPy"
1378 match = _pypy_sys_version_parser.match(sys_version)
1379 if match is None:
1380 raise ValueError("failed to parse PyPy sys.version: %s" %
1381 repr(sys_version))
1382 version, buildno, builddate, buildtime = match.groups()
1383 compiler = ""
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001384
1385 else:
1386 # CPython
1387 match = _sys_version_parser.match(sys_version)
1388 if match is None:
1389 raise ValueError(
1390 'failed to parse CPython sys.version: %s' %
1391 repr(sys_version))
1392 version, buildno, builddate, buildtime, compiler = \
1393 match.groups()
Benjamin Petersone549ead2009-03-28 21:42:05 +00001394 name = 'CPython'
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001395 builddate = builddate + ' ' + buildtime
1396
Georg Brandl82562422011-03-05 21:09:22 +01001397 if hasattr(sys, '_mercurial'):
1398 _, branch, revision = sys._mercurial
1399 elif hasattr(sys, 'subversion'):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001400 # sys.subversion was added in Python 2.5
1401 _, branch, revision = sys.subversion
1402 else:
1403 branch = ''
1404 revision = ''
1405
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001406 # Add the patchlevel version if missing
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001407 l = version.split('.')
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001408 if len(l) == 2:
1409 l.append('0')
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001410 version = '.'.join(l)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001411
1412 # Build and cache the result
1413 result = (name, version, branch, revision, buildno, builddate, compiler)
1414 _sys_version_cache[sys_version] = result
1415 return result
1416
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001417def python_implementation():
1418
1419 """ Returns a string identifying the Python implementation.
1420
1421 Currently, the following implementations are identified:
Ezio Melottif16898b2011-05-04 18:37:50 +03001422 'CPython' (C implementation of Python),
1423 'IronPython' (.NET implementation of Python),
1424 'Jython' (Java implementation of Python),
1425 'PyPy' (Python implementation of Python).
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001426
1427 """
1428 return _sys_version()[0]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001429
1430def python_version():
1431
1432 """ Returns the Python version as string 'major.minor.patchlevel'
1433
1434 Note that unlike the Python sys.version, the returned value
1435 will always include the patchlevel (it defaults to 0).
1436
1437 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001438 return _sys_version()[1]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001439
1440def python_version_tuple():
1441
1442 """ Returns the Python version as tuple (major, minor, patchlevel)
1443 of strings.
1444
1445 Note that unlike the Python sys.version, the returned value
1446 will always include the patchlevel (it defaults to 0).
1447
1448 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001449 return tuple(_sys_version()[1].split('.'))
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001450
1451def python_branch():
1452
1453 """ Returns a string identifying the Python implementation
1454 branch.
1455
1456 For CPython this is the Subversion branch from which the
1457 Python binary was built.
1458
1459 If not available, an empty string is returned.
1460
1461 """
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001462
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001463 return _sys_version()[2]
1464
1465def python_revision():
1466
1467 """ Returns a string identifying the Python implementation
1468 revision.
1469
1470 For CPython this is the Subversion revision from which the
1471 Python binary was built.
1472
1473 If not available, an empty string is returned.
1474
1475 """
1476 return _sys_version()[3]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001477
1478def python_build():
1479
1480 """ Returns a tuple (buildno, builddate) stating the Python
1481 build number and date as strings.
1482
1483 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001484 return _sys_version()[4:6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001485
1486def python_compiler():
1487
1488 """ Returns a string identifying the compiler used for compiling
1489 Python.
1490
1491 """
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001492 return _sys_version()[6]
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001493
1494### The Opus Magnum of platform strings :-)
1495
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001496_platform_cache = {}
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001497
1498def platform(aliased=0, terse=0):
1499
1500 """ Returns a single string identifying the underlying platform
1501 with as much useful information as possible (but no more :).
Tim Peters0eadaac2003-04-24 16:02:54 +00001502
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001503 The output is intended to be human readable rather than
1504 machine parseable. It may look different on different
1505 platforms and this is intended.
1506
1507 If "aliased" is true, the function will use aliases for
1508 various platforms that report system names which differ from
1509 their common names, e.g. SunOS will be reported as
1510 Solaris. The system_alias() function is used to implement
1511 this.
1512
1513 Setting terse to true causes the function to return only the
1514 absolute minimum information needed to identify the platform.
1515
1516 """
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001517 result = _platform_cache.get((aliased, terse), None)
1518 if result is not None:
1519 return result
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001520
1521 # Get uname information and then apply platform specific cosmetics
1522 # to it...
1523 system,node,release,version,machine,processor = uname()
1524 if machine == processor:
1525 processor = ''
1526 if aliased:
1527 system,release,version = system_alias(system,release,version)
1528
1529 if system == 'Windows':
1530 # MS platforms
1531 rel,vers,csd,ptype = win32_ver(version)
1532 if terse:
1533 platform = _platform(system,release)
1534 else:
1535 platform = _platform(system,release,version,csd)
1536
1537 elif system in ('Linux',):
1538 # Linux based systems
1539 distname,distversion,distid = dist('')
1540 if distname and not terse:
1541 platform = _platform(system,release,machine,processor,
1542 'with',
1543 distname,distversion,distid)
1544 else:
1545 # If the distribution name is unknown check for libc vs. glibc
1546 libcname,libcversion = libc_ver(sys.executable)
1547 platform = _platform(system,release,machine,processor,
1548 'with',
1549 libcname+libcversion)
1550 elif system == 'Java':
1551 # Java platforms
1552 r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001553 if terse or not os_name:
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001554 platform = _platform(system,release,version)
1555 else:
1556 platform = _platform(system,release,version,
1557 'on',
1558 os_name,os_version,os_arch)
1559
1560 elif system == 'MacOS':
1561 # MacOS platforms
1562 if terse:
1563 platform = _platform(system,release)
1564 else:
1565 platform = _platform(system,release,machine)
1566
1567 else:
1568 # Generic handler
1569 if terse:
1570 platform = _platform(system,release)
1571 else:
1572 bits,linkage = architecture(sys.executable)
1573 platform = _platform(system,release,machine,processor,bits,linkage)
Tim Peters0eadaac2003-04-24 16:02:54 +00001574
Marc-André Lemburg91e83e22004-03-25 18:35:12 +00001575 _platform_cache[(aliased, terse)] = platform
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001576 return platform
1577
1578### Command line interface
1579
1580if __name__ == '__main__':
1581 # Default is to print the aliased verbose platform string
Tim Peters0eadaac2003-04-24 16:02:54 +00001582 terse = ('terse' in sys.argv or '--terse' in sys.argv)
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001583 aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001584 print(platform(aliased,terse))
Marc-André Lemburg246d8472003-04-24 11:36:11 +00001585 sys.exit(0)