platform.py 40.5 KB
Newer Older
1
#!/usr/bin/env python3
2

Brett Cannon's avatar
Brett Cannon committed
3
""" This module tries to retrieve as much platform-identifying data as
4 5 6 7 8 9 10 11 12
    possible. It makes this information available via function APIs.

    If called from the command line, it prints the platform
    information concatenated as single string to stdout. The output
    format is useable as part of a filename.

"""
#    This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
#    If you find problems, please submit bug reports/patches via the
Benjamin Peterson's avatar
Benjamin Peterson committed
13
#    Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
14 15 16 17 18 19
#
#    Still needed:
#    * support for MS-DOS (PythonDX ?)
#    * support for Amiga and other still unsupported platforms running Python
#    * support for additional Linux distributions
#
Brett Cannon's avatar
Brett Cannon committed
20
#    Many thanks to all those who helped adding platform-specific
21 22 23 24 25 26 27
#    checks (in no particular order):
#
#      Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
#      Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
#      Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
#      Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
#      Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
28 29
#      Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter, Steve
#      Dower
30 31
#
#    History:
32 33 34
#
#    <see CVS and SVN checkin messages for history>
#
35
#    1.0.8 - changed Windows support to read version from kernel32.dll
36
#    1.0.7 - added DEV_NULL
37 38 39
#    1.0.6 - added linux_distribution()
#    1.0.5 - fixed Java support to allow running the module on Jython
#    1.0.4 - added IronPython support
40
#    1.0.3 - added normalization of Windows system name
41
#    1.0.2 - added more Windows support
42
#    1.0.1 - reformatted to make doc.py happy
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#    1.0.0 - reformatted a bit and checked into Python CVS
#    0.8.0 - added sys.version parser and various new access
#            APIs (python_version(), python_compiler(), etc.)
#    0.7.2 - fixed architecture() to use sizeof(pointer) where available
#    0.7.1 - added support for Caldera OpenLinux
#    0.7.0 - some fixes for WinCE; untabified the source file
#    0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
#            vms_lib.getsyi() configured
#    0.6.1 - added code to prevent 'uname -p' on platforms which are
#            known not to support it
#    0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
#            did some cleanup of the interfaces - some APIs have changed
#    0.5.5 - fixed another type in the MacOS code... should have
#            used more coffee today ;-)
#    0.5.4 - fixed a few typos in the MacOS code
#    0.5.3 - added experimental MacOS support; added better popen()
#            workarounds in _syscmd_ver() -- still not 100% elegant
#            though
#    0.5.2 - fixed uname() to return '' instead of 'unknown' in all
#            return values (the system uname command tends to return
63
#            'unknown' instead of just leaving the field empty)
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
#    0.5.1 - included code for slackware dist; added exception handlers
#            to cover up situations where platforms don't have os.popen
#            (e.g. Mac) or fail on socket.gethostname(); fixed libc
#            detection RE
#    0.5.0 - changed the API names referring to system commands to *syscmd*;
#            added java_ver(); made syscmd_ver() a private
#            API (was system_ver() in previous versions) -- use uname()
#            instead; extended the win32_ver() to also return processor
#            type information
#    0.4.0 - added win32_ver() and modified the platform() output for WinXX
#    0.3.4 - fixed a bug in _follow_symlinks()
#    0.3.3 - fixed popen() and "file" command invokation bugs
#    0.3.2 - added architecture() API and support for it in platform()
#    0.3.1 - fixed syscmd_ver() RE to support Windows NT
#    0.3.0 - added system alias support
#    0.2.3 - removed 'wince' again... oh well.
#    0.2.2 - added 'wince' to syscmd_ver() supported platforms
#    0.2.1 - added cache logic and changed the platform string format
#    0.2.0 - changed the API to use functions instead of module globals
#            since some action take too long to be run on module import
#    0.1.0 - first release
#
#    You can always get the latest version of this module at:
#
#             http://www.egenix.com/files/python/platform.py
#
#    If that URL should fail, try contacting the author.

__copyright__ = """
    Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
94
    Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

    Permission to use, copy, modify, and distribute this software and its
    documentation for any purpose and without fee or royalty is hereby granted,
    provided that the above copyright notice appear in all copies and that
    both that copyright notice and this permission notice appear in
    supporting documentation or portions thereof, including modifications,
    that you make.

    EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
    THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
    INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
    FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
    NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
    WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !

"""

113
__version__ = '1.0.8'
114

115
import collections
116
import sys, os, re, subprocess
117

118 119
import warnings

120 121 122 123 124 125 126 127
### Globals & Constants

# Determine the platform's /dev/null device
try:
    DEV_NULL = os.devnull
except AttributeError:
    # os.devnull was added in Python 2.4, so emulate it for earlier
    # Python versions
128
    if sys.platform in ('dos', 'win32', 'win16'):
129 130 131 132 133 134
        # Use the old CP/M NUL as device name
        DEV_NULL = 'NUL'
    else:
        # Standard Unix uses /dev/null
        DEV_NULL = '/dev/null'

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
# Helper for comparing two version number strings.
# Based on the description of the PHP's version_compare():
# http://php.net/manual/en/function.version-compare.php

_ver_stages = {
    # any string not found in this dict, will get 0 assigned
    'dev': 10,
    'alpha': 20, 'a': 20,
    'beta': 30, 'b': 30,
    'c': 40,
    'RC': 50, 'rc': 50,
    # number, will get 100 assigned
    'pl': 200, 'p': 200,
}

_component_re = re.compile(r'([0-9]+|[._+-])')

def _comparable_version(version):
    result = []
    for v in _component_re.split(version):
        if v not in '._+-':
            try:
                v = int(v, 10)
                t = 100
            except ValueError:
                t = _ver_stages.get(v, 0)
            result.extend((t, v))
    return result

164 165
### Platform specific APIs

166 167 168 169 170
_libc_search = re.compile(b'(__libc_init)'
                          b'|'
                          b'(GLIBC_([0-9.]+))'
                          b'|'
                          br'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)', re.ASCII)
171

172
def libc_ver(executable=sys.executable, lib='', version='', chunksize=16384):
173

Brett Cannon's avatar
Brett Cannon committed
174 175
    """ Tries to determine the libc version that the file executable
        (which defaults to the Python interpreter) is linked against.
176 177 178 179 180

        Returns a tuple of strings (lib,version) which default to the
        given parameters in case the lookup fails.

        Note that the function has intimate knowledge of how different
Brett Cannon's avatar
Brett Cannon committed
181 182
        libc versions add symbols to the executable and thus is probably
        only useable for executables compiled using gcc.
183 184 185 186

        The file is read and scanned in chunks of chunksize bytes.

    """
187
    V = _comparable_version
188 189 190 191 192
    if hasattr(os.path, 'realpath'):
        # Python 2.2 introduced os.path.realpath(); it is used
        # here to work around problems with Cygwin not being
        # able to open symlinks for reading
        executable = os.path.realpath(executable)
193 194 195
    with open(executable, 'rb') as f:
        binary = f.read(chunksize)
        pos = 0
196
        while pos < len(binary):
197 198 199 200
            if b'libc' in binary or b'GLIBC' in binary:
                m = _libc_search.search(binary, pos)
            else:
                m = None
201 202 203 204 205 206 207
            if not m or m.end() == len(binary):
                chunk = f.read(chunksize)
                if chunk:
                    binary = binary[max(pos, len(binary) - 1000):] + chunk
                    pos = 0
                    continue
                if not m:
208 209 210 211 212
                    break
            libcinit, glibc, glibcversion, so, threads, soversion = [
                s.decode('latin1') if s is not None else s
                for s in m.groups()]
            if libcinit and not lib:
213
                lib = 'libc'
214 215 216 217
            elif glibc:
                if lib != 'glibc':
                    lib = 'glibc'
                    version = glibcversion
218
                elif V(glibcversion) > V(version):
219 220 221 222
                    version = glibcversion
            elif so:
                if lib != 'glibc':
                    lib = 'libc'
223
                    if soversion and (not version or V(soversion) > V(version)):
224 225 226 227
                        version = soversion
                    if threads and version[-len(threads):] != threads:
                        version = version + threads
            pos = m.end()
228
    return lib, version
229

230
def _dist_try_harder(distname, version, id):
231

Tim Peters's avatar
Tim Peters committed
232
    """ Tries some special tricks to get the distribution
233 234 235 236 237 238 239 240 241
        information in case the default method fails.

        Currently supports older SuSE Linux, Caldera OpenLinux and
        Slackware Linux distributions.

    """
    if os.path.exists('/var/adm/inst-log/info'):
        # SuSE Linux stores distribution information in that file
        distname = 'SuSE'
242
        for line in open('/var/adm/inst-log/info'):
243
            tv = line.split()
244
            if len(tv) == 2:
245
                tag, value = tv
246 247 248
            else:
                continue
            if tag == 'MIN_DIST_VERSION':
249
                version = value.strip()
250
            elif tag == 'DIST_IDENT':
251
                values = value.split('-')
252
                id = values[2]
253
        return distname, version, id
254 255 256

    if os.path.exists('/etc/.installed'):
        # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
257
        for line in open('/etc/.installed'):
258
            pkg = line.split('-')
259 260 261
            if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
                # XXX does Caldera support non Intel platforms ? If yes,
                #     where can we find the needed id ?
262
                return 'OpenLinux', pkg[1], id
263 264

    if os.path.isdir('/usr/lib/setup'):
265
        # Check for slackware version tag file (thanks to Greg Andruk)
266
        verfiles = os.listdir('/usr/lib/setup')
267
        for n in range(len(verfiles)-1, -1, -1):
268 269 270 271 272 273
            if verfiles[n][:14] != 'slack-version-':
                del verfiles[n]
        if verfiles:
            verfiles.sort()
            distname = 'slackware'
            version = verfiles[-1][14:]
274
            return distname, version, id
275

276
    return distname, version, id
277

278
def popen(cmd, mode='r', bufsize=-1):
279 280 281

    """ Portable popen() interface.
    """
282 283
    import warnings
    warnings.warn('use os.popen instead', DeprecationWarning, stacklevel=2)
284
    return os.popen(cmd, mode, bufsize)
285

286

287
def _norm_version(version, build=''):
288

Brett Cannon's avatar
Brett Cannon committed
289
    """ Normalize the version and build strings and return a single
Walter Dörwald's avatar
Walter Dörwald committed
290
        version string using the format major.minor.build (or patchlevel).
291
    """
292
    l = version.split('.')
293 294 295
    if build:
        l.append(build)
    try:
296
        ints = map(int, l)
297 298 299
    except ValueError:
        strings = l
    else:
300
        strings = list(map(str, ints))
301
    version = '.'.join(strings[:3])
302 303
    return version

304
_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
305 306
                         r'.*'
                         r'\[.* ([\d.]+)\])')
307 308 309 310 311 312 313 314 315

# Examples of VER command output:
#
#   Windows 2000:  Microsoft Windows 2000 [Version 5.00.2195]
#   Windows XP:    Microsoft Windows XP [Version 5.1.2600]
#   Windows Vista: Microsoft Windows [Version 6.0.6002]
#
# Note that the "Version" string gets localized on different
# Windows versions.
316

317
def _syscmd_ver(system='', release='', version='',
318

319
               supported_platforms=('win32', 'win16', 'dos')):
320 321

    """ Tries to figure out the OS version used and returns
322
        a tuple (system, release, version).
Tim Peters's avatar
Tim Peters committed
323

324
        It uses the "ver" shell command for this which is known
325
        to exists on Windows, DOS. XXX Others too ?
326 327 328 329 330 331

        In case this fails, the given parameters are used as
        defaults.

    """
    if sys.platform not in supported_platforms:
332
        return system, release, version
333 334

    # Try some common cmd strings
335
    for cmd in ('ver', 'command /c ver', 'cmd /c ver'):
336
        try:
337
            pipe = os.popen(cmd)
338 339
            info = pipe.read()
            if pipe.close():
340
                raise OSError('command failed')
341
            # XXX How can I suppress shell errors from being written
342
            #     to stderr ?
343
        except OSError as why:
344
            #print 'Command %s failed: %s' % (cmd, why)
345 346 347 348
            continue
        else:
            break
    else:
349
        return system, release, version
350 351

    # Parse the output
352
    info = info.strip()
353
    m = _ver_output.match(info)
354
    if m is not None:
355
        system, release, version = m.groups()
356 357 358 359 360 361 362 363
        # Strip trailing dots from version and release
        if release[-1] == '.':
            release = release[:-1]
        if version[-1] == '.':
            version = version[:-1]
        # Normalize the version and build strings (eliminating additional
        # zeros)
        version = _norm_version(version)
364
    return system, release, version
365

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
_WIN32_CLIENT_RELEASES = {
    (5, 0): "2000",
    (5, 1): "XP",
    # Strictly, 5.2 client is XP 64-bit, but platform.py historically
    # has always called it 2003 Server
    (5, 2): "2003Server",
    (5, None): "post2003",

    (6, 0): "Vista",
    (6, 1): "7",
    (6, 2): "8",
    (6, 3): "8.1",
    (6, None): "post8.1",

    (10, 0): "10",
    (10, None): "post10",
}

# Server release name lookup will default to client names if necessary
_WIN32_SERVER_RELEASES = {
    (5, 2): "2003Server",

    (6, 0): "2008Server",
    (6, 1): "2008ServerR2",
    (6, 2): "2012Server",
    (6, 3): "2012ServerR2",
    (6, None): "post2012ServerR2",
}

def win32_ver(release='', version='', csd='', ptype=''):
396 397 398 399
    try:
        from sys import getwindowsversion
    except ImportError:
        return release, version, csd, ptype
400
    try:
401
        from winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
402
    except ImportError:
403
        from _winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
404

405
    winver = getwindowsversion()
406
    maj, min, build = winver.platform_version or winver[:3]
407
    version = '{0}.{1}.{2}'.format(maj, min, build)
408

409 410 411
    release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or
               _WIN32_CLIENT_RELEASES.get((maj, None)) or
               release)
412

413 414 415 416
    # getwindowsversion() reflect the compatibility mode Python is
    # running under, and so the service pack value is only going to be
    # valid if the versions match.
    if winver[:2] == (maj, min):
417
        try:
418
            csd = 'SP{}'.format(winver.service_pack_major)
419
        except AttributeError:
420 421
            if csd[:13] == 'Service Pack ':
                csd = 'SP' + csd[13:]
422

423
    # VER_NT_SERVER = 3
424
    if getattr(winver, 'product_type', None) == 3:
425 426 427
        release = (_WIN32_SERVER_RELEASES.get((maj, min)) or
                   _WIN32_SERVER_RELEASES.get((maj, None)) or
                   release)
428

429
    key = None
430
    try:
431 432 433
        key = OpenKeyEx(HKEY_LOCAL_MACHINE,
                        r'SOFTWARE\Microsoft\Windows NT\CurrentVersion')
        ptype = QueryValueEx(key, 'CurrentType')[0]
434
    except:
435 436 437 438 439
        pass
    finally:
        if key:
            CloseKey(key)

440
    return release, version, csd, ptype
441

442

443 444 445 446 447 448 449
def _mac_ver_xml():
    fn = '/System/Library/CoreServices/SystemVersion.plist'
    if not os.path.exists(fn):
        return None

    try:
        import plistlib
450
    except ImportError:
451 452
        return None

453 454
    with open(fn, 'rb') as f:
        pl = plistlib.load(f)
455
    release = pl['ProductVersion']
456
    versioninfo = ('', '', '')
457
    machine = os.uname().machine
458
    if machine in ('ppc', 'Power Macintosh'):
Ezio Melotti's avatar
Ezio Melotti committed
459
        # Canonical name
460 461
        machine = 'PowerPC'

462
    return release, versioninfo, machine
463 464


465
def mac_ver(release='', versioninfo=('', '', ''), machine=''):
466 467 468 469 470

    """ Get MacOS version information and return it as tuple (release,
        versioninfo, machine) with versioninfo being a tuple (version,
        dev_stage, non_release_version).

471
        Entries which cannot be determined are set to the parameter values
472 473 474 475 476 477 478 479 480 481
        which default to ''. All tuple entries are strings.
    """

    # First try reading the information from an XML file which should
    # always be present
    info = _mac_ver_xml()
    if info is not None:
        return info

    # If that also doesn't work return the default values
482
    return release, versioninfo, machine
483

484
def _java_getprop(name, default):
485 486 487

    from java.lang import System
    try:
488 489 490 491 492
        value = System.getProperty(name)
        if value is None:
            return default
        return value
    except AttributeError:
493 494
        return default

495
def java_ver(release='', vendor='', vminfo=('', '', ''), osinfo=('', '', '')):
Tim Peters's avatar
Tim Peters committed
496

Brett Cannon's avatar
Brett Cannon committed
497
    """ Version interface for Jython.
498

499 500 501
        Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being
        a tuple (vm_name, vm_release, vm_vendor) and osinfo being a
        tuple (os_name, os_version, os_arch).
502 503 504 505 506 507 508 509

        Values which cannot be determined are set to the defaults
        given as parameters (which all default to '').

    """
    # Import the needed APIs
    try:
        import java.lang
510
    except ImportError:
511
        return release, vendor, vminfo, osinfo
512

513 514 515 516 517 518 519 520 521 522 523 524 525 526
    vendor = _java_getprop('java.vendor', vendor)
    release = _java_getprop('java.version', release)
    vm_name, vm_release, vm_vendor = vminfo
    vm_name = _java_getprop('java.vm.name', vm_name)
    vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
    vm_release = _java_getprop('java.vm.version', vm_release)
    vminfo = vm_name, vm_release, vm_vendor
    os_name, os_version, os_arch = osinfo
    os_arch = _java_getprop('java.os.arch', os_arch)
    os_name = _java_getprop('java.os.name', os_name)
    os_version = _java_getprop('java.os.version', os_version)
    osinfo = os_name, os_version, os_arch

    return release, vendor, vminfo, osinfo
527 528 529

### System name aliasing

530
def system_alias(system, release, version):
531

532
    """ Returns (system, release, version) aliased to common
533 534 535 536 537 538 539 540 541
        marketing names used for some systems.

        It also does some reordering of the information in some cases
        where it would otherwise cause confusion.

    """
    if system == 'Rhapsody':
        # Apple's BSD derivative
        # XXX How can we determine the marketing release number ?
542
        return 'MacOS X Server', system+release, version
543 544 545 546 547

    elif system == 'SunOS':
        # Sun's OS
        if release < '5':
            # These releases use the old name SunOS
548
            return system, release, version
549
        # Modify release (marketing release = SunOS release - 3)
550
        l = release.split('.')
551 552 553 554 555 556 557 558
        if l:
            try:
                major = int(l[0])
            except ValueError:
                pass
            else:
                major = major - 3
                l[0] = str(major)
559
                release = '.'.join(l)
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
        if release < '6':
            system = 'Solaris'
        else:
            # XXX Whatever the new SunOS marketing name is...
            system = 'Solaris'

    elif system == 'IRIX64':
        # IRIX reports IRIX64 on platforms with 64-bit support; yet it
        # is really a version and not a different platform, since 32-bit
        # apps are also supported..
        system = 'IRIX'
        if version:
            version = version + ' (64bit)'
        else:
            version = '64bit'

576
    elif system in ('win32', 'win16'):
577 578 579
        # In case one of the other tricks
        system = 'Windows'

580
    return system, release, version
581 582 583 584 585 586 587 588 589

### Various internal helpers

def _platform(*args):

    """ Helper to format the platform string in a filename
        compatible format e.g. "system-version-machine".
    """
    # Format the platform string
590
    platform = '-'.join(x.strip() for x in filter(len, args))
591 592

    # Cleanup some possible filename obstacles...
593 594 595 596 597 598 599 600
    platform = platform.replace(' ', '_')
    platform = platform.replace('/', '-')
    platform = platform.replace('\\', '-')
    platform = platform.replace(':', '-')
    platform = platform.replace(';', '-')
    platform = platform.replace('"', '-')
    platform = platform.replace('(', '-')
    platform = platform.replace(')', '-')
601 602

    # No need to report 'unknown' information...
603
    platform = platform.replace('unknown', '')
604 605 606

    # Fold '--'s and remove trailing '-'
    while 1:
607
        cleaned = platform.replace('--', '-')
608 609 610 611 612 613 614 615 616 617 618 619 620 621
        if cleaned == platform:
            break
        platform = cleaned
    while platform[-1] == '-':
        platform = platform[:-1]

    return platform

def _node(default=''):

    """ Helper to determine the node name of this machine.
    """
    try:
        import socket
622
    except ImportError:
623 624 625 626
        # No sockets...
        return default
    try:
        return socket.gethostname()
627
    except OSError:
628 629 630 631 632 633 634 635
        # Still not working...
        return default

def _follow_symlinks(filepath):

    """ In case filepath is a symlink, follow it until a
        real file is reached.
    """
636
    filepath = os.path.abspath(filepath)
637 638
    while os.path.islink(filepath):
        filepath = os.path.normpath(
639
            os.path.join(os.path.dirname(filepath), os.readlink(filepath)))
640 641
    return filepath

642
def _syscmd_uname(option, default=''):
643 644 645

    """ Interface to the system's uname command.
    """
646
    if sys.platform in ('dos', 'win32', 'win16'):
647 648 649
        # XXX Others too ?
        return default
    try:
650
        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
651
    except (AttributeError, OSError):
652
        return default
653
    output = f.read().strip()
654 655 656 657 658 659
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output

660
def _syscmd_file(target, default=''):
661 662 663 664

    """ Interface to the system's file command.

        The function uses the -b option of the file command to have it
665 666
        omit the filename in its output. Follow the symlinks. It returns
        default in case the command should fail.
667 668

    """
669
    if sys.platform in ('dos', 'win32', 'win16'):
670 671
        # XXX Others too ?
        return default
672
    target = _follow_symlinks(target)
673
    try:
674 675
        proc = subprocess.Popen(['file', target],
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
676

677
    except (AttributeError, OSError):
678
        return default
679
    output = proc.communicate()[0].decode('latin-1')
680
    rc = proc.wait()
681 682 683 684 685 686 687 688 689 690
    if not output or rc:
        return default
    else:
        return output

### Information about the used architecture

# Default values for architecture; non-empty strings override the
# defaults given as parameters
_default_architecture = {
691 692 693
    'win32': ('', 'WindowsPE'),
    'win16': ('', 'Windows'),
    'dos': ('', 'MSDOS'),
694 695
}

696
def architecture(executable=sys.executable, bits='', linkage=''):
697 698

    """ Queries the given executable (defaults to the Python interpreter
Brett Cannon's avatar
Brett Cannon committed
699
        binary) for various architecture information.
700

701
        Returns a tuple (bits, linkage) which contains information about
702 703 704 705 706 707 708 709 710 711
        the bit architecture and the linkage format used for the
        executable. Both values are returned as strings.

        Values that cannot be determined are returned as given by the
        parameter presets. If bits is given as '', the sizeof(pointer)
        (or sizeof(long) on Python version < 1.5.2) is used as
        indicator for the supported pointer size.

        The function relies on the system's "file" command to do the
        actual work. This is available on most if not all Unix
Brett Cannon's avatar
Brett Cannon committed
712 713 714
        platforms. On some non-Unix platforms where the "file" command
        does not exist and the executable is set to the Python interpreter
        binary defaults from _default_architecture are used.
715 716 717 718 719 720 721 722 723 724 725 726

    """
    # Use the sizeof(pointer) as default number of bits if nothing
    # else is given as default.
    if not bits:
        import struct
        try:
            size = struct.calcsize('P')
        except struct.error:
            # Older installations can only query longs
            size = struct.calcsize('l')
        bits = str(size*8) + 'bit'
Tim Peters's avatar
Tim Peters committed
727

728
    # Get data from the 'file' system command
729
    if executable:
730
        fileout = _syscmd_file(executable, '')
731
    else:
732
        fileout = ''
733

734
    if not fileout and \
735 736
       executable == sys.executable:
        # "file" command did not return anything; we'll try to provide
Tim Peters's avatar
Tim Peters committed
737
        # some sensible defaults then...
738
        if sys.platform in _default_architecture:
739
            b, l = _default_architecture[sys.platform]
740 741 742 743
            if b:
                bits = b
            if l:
                linkage = l
744
        return bits, linkage
745 746 747

    if 'executable' not in fileout:
        # Format not supported
748
        return bits, linkage
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

    # Bits
    if '32-bit' in fileout:
        bits = '32bit'
    elif 'N32' in fileout:
        # On Irix only
        bits = 'n32bit'
    elif '64-bit' in fileout:
        bits = '64bit'

    # Linkage
    if 'ELF' in fileout:
        linkage = 'ELF'
    elif 'PE' in fileout:
        # E.g. Windows uses this format
        if 'Windows' in fileout:
            linkage = 'WindowsPE'
        else:
            linkage = 'PE'
    elif 'COFF' in fileout:
        linkage = 'COFF'
    elif 'MS-DOS' in fileout:
        linkage = 'MSDOS'
    else:
        # XXX the A.OUT format also falls under this class...
        pass

776
    return bits, linkage
777 778

### Portable uname() interface
Tim Peters's avatar
Tim Peters committed
779

780 781 782
uname_result = collections.namedtuple("uname_result",
                    "system node release version machine processor")

783 784 785 786 787
_uname_cache = None

def uname():

    """ Fairly portable uname interface. Returns a tuple
788
        of strings (system, node, release, version, machine, processor)
789 790 791
        identifying the underlying platform.

        Note that unlike the os.uname function this also returns
Brett Cannon's avatar
Brett Cannon committed
792
        possible processor information as an additional tuple entry.
793 794 795 796 797

        Entries which cannot be determined are set to ''.

    """
    global _uname_cache
798
    no_os_uname = 0
799 800 801 802

    if _uname_cache is not None:
        return _uname_cache

803 804
    processor = ''

805 806
    # Get some infos from the builtin os.uname API...
    try:
807
        system, node, release, version, machine = os.uname()
808
    except AttributeError:
809 810
        no_os_uname = 1

811
    if no_os_uname or not list(filter(None, (system, node, release, version, machine))):
812 813 814 815 816 817 818 819 820
        # Hmm, no there is either no uname or uname has returned
        #'unknowns'... we'll have to poke around the system then.
        if no_os_uname:
            system = sys.platform
            release = ''
            version = ''
            node = _node()
            machine = ''

821
        use_syscmd_ver = 1
822 823 824

        # Try win32_ver() on win32 platforms
        if system == 'win32':
825
            release, version, csd, ptype = win32_ver()
826 827
            if release and version:
                use_syscmd_ver = 0
828
            # Try to use the PROCESSOR_* environment variables
829 830 831
            # available on Win XP and later; see
            # http://support.microsoft.com/kb/888731 and
            # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
832
            if not machine:
833 834 835 836 837
                # WOW64 processes mask the native architecture
                if "PROCESSOR_ARCHITEW6432" in os.environ:
                    machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
                else:
                    machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
838 839
            if not processor:
                processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
Tim Peters's avatar
Tim Peters committed
840

841 842 843
        # Try the 'ver' system command available on some
        # platforms
        if use_syscmd_ver:
844
            system, release, version = _syscmd_ver(system)
845 846 847 848
            # Normalize system to what win32_ver() normally returns
            # (_syscmd_ver() tends to return the vendor name as well)
            if system == 'Microsoft Windows':
                system = 'Windows'
849 850 851 852 853 854 855 856 857 858
            elif system == 'Microsoft' and release == 'Windows':
                # Under Windows Vista and Windows Server 2008,
                # Microsoft changed the output of the ver command. The
                # release is no longer printed.  This causes the
                # system and release to be misidentified.
                system = 'Windows'
                if '6.0' == version[:3]:
                    release = 'Vista'
                else:
                    release = ''
859 860 861

        # In case we still don't know anything useful, we'll try to
        # help ourselves
862
        if system in ('win32', 'win16'):
863 864 865 866 867 868 869 870
            if not version:
                if system == 'win32':
                    version = '32bit'
                else:
                    version = '16bit'
            system = 'Windows'

        elif system[:4] == 'java':
871
            release, vendor, vminfo, osinfo = java_ver()
872
            system = 'Java'
873
            version = ', '.join(vminfo)
874 875 876
            if not version:
                version = vendor

877 878 879 880 881 882 883 884 885
    # System specific extensions
    if system == 'OpenVMS':
        # OpenVMS seems to have release and version mixed up
        if not release or release == '0':
            release = version
            version = ''
        # Get processor information
        try:
            import vms_lib
886
        except ImportError:
887
            pass
888
        else:
889
            csid, cpu_number = vms_lib.getsyi('SYI$_CPU', 0)
890 891 892 893 894 895
            if (cpu_number >= 128):
                processor = 'Alpha'
            else:
                processor = 'VAX'
    if not processor:
        # Get processor information from the uname system command
896
        processor = _syscmd_uname('-p', '')
897

898
    #If any unknowns still exist, replace them with ''s, which are more portable
899 900 901 902 903 904 905 906 907 908 909 910
    if system == 'unknown':
        system = ''
    if node == 'unknown':
        node = ''
    if release == 'unknown':
        release = ''
    if version == 'unknown':
        version = ''
    if machine == 'unknown':
        machine = ''
    if processor == 'unknown':
        processor = ''
911 912 913 914 915 916

    #  normalize name
    if system == 'Microsoft' and release == 'Windows':
        system = 'Windows'
        release = 'Vista'

917 918
    _uname_cache = uname_result(system, node, release, version,
                                machine, processor)
919 920 921 922 923 924 925 926 927 928 929
    return _uname_cache

### Direct interfaces to some of the uname() return values

def system():

    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.

        An empty string is returned if the value cannot be determined.

    """
930
    return uname().system
931 932 933

def node():

Brett Cannon's avatar
Brett Cannon committed
934 935
    """ Returns the computer's network name (which may not be fully
        qualified)
936 937 938 939

        An empty string is returned if the value cannot be determined.

    """
940
    return uname().node
941 942 943 944 945 946 947 948

def release():

    """ Returns the system's release, e.g. '2.2.0' or 'NT'

        An empty string is returned if the value cannot be determined.

    """
949
    return uname().release
950 951 952 953 954 955 956 957

def version():

    """ Returns the system's release version, e.g. '#3 on degas'

        An empty string is returned if the value cannot be determined.

    """
958
    return uname().version
959 960 961 962 963 964 965 966

def machine():

    """ Returns the machine type, e.g. 'i386'

        An empty string is returned if the value cannot be determined.

    """
967
    return uname().machine
968 969 970 971 972 973 974 975 976 977 978

def processor():

    """ Returns the (true) processor name, e.g. 'amdk6'

        An empty string is returned if the value cannot be
        determined. Note that many platforms do not provide this
        information or simply return the same value as for machine(),
        e.g.  NetBSD does this.

    """
979
    return uname().processor
980 981 982

### Various APIs for extracting information from sys.version

983
_sys_version_parser = re.compile(
984 985 986 987 988
    r'([\w.+]+)\s*'  # "version<space>"
    r'\(#?([^,]+)'  # "(#buildno"
    r'(?:,\s*([\w ]*)'  # ", builddate"
    r'(?:,\s*([\w :]*))?)?\)\s*'  # ", buildtime)<space>"
    r'\[([^\]]+)\]?', re.ASCII)  # "[compiler]"
989 990 991

_ironpython_sys_version_parser = re.compile(
    r'IronPython\s*'
992 993 994
    r'([\d\.]+)'
    r'(?: \(([\d\.]+)\))?'
    r' on (.NET [\d\.]+)', re.ASCII)
995

996 997 998
# IronPython covering 2.6 and 2.7
_ironpython26_sys_version_parser = re.compile(
    r'([\d.]+)\s*'
999 1000 1001
    r'\(IronPython\s*'
    r'[\d.]+\s*'
    r'\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
1002 1003
)

Benjamin Peterson's avatar
Benjamin Peterson committed
1004 1005
_pypy_sys_version_parser = re.compile(
    r'([\w.+]+)\s*'
1006 1007
    r'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
    r'\[PyPy [^\]]+\]?')
Benjamin Peterson's avatar
Benjamin Peterson committed
1008

1009 1010 1011
_sys_version_cache = {}

def _sys_version(sys_version=None):
1012 1013

    """ Returns a parsed version of Python's sys.version as tuple
1014 1015 1016 1017
        (name, version, branch, revision, buildno, builddate, compiler)
        referring to the Python implementation name, version, branch,
        revision, build number, build date/time as string and the compiler
        identification string.
1018 1019 1020 1021 1022

        Note that unlike the Python sys.version, the returned value
        for the Python version will always include the patchlevel (it
        defaults to '.0').

1023 1024 1025 1026 1027 1028 1029
        The function returns empty strings for tuple entries that
        cannot be determined.

        sys_version may be given to parse an alternative version
        string, e.g. if the version was read from a different Python
        interpreter.

1030
    """
1031 1032 1033
    # Get the Python version
    if sys_version is None:
        sys_version = sys.version
1034

1035 1036 1037 1038 1039 1040
    # Try the cache first
    result = _sys_version_cache.get(sys_version, None)
    if result is not None:
        return result

    # Parse it
1041
    if 'IronPython' in sys_version:
1042 1043
        # IronPython
        name = 'IronPython'
1044 1045 1046 1047 1048
        if sys_version.startswith('IronPython'):
            match = _ironpython_sys_version_parser.match(sys_version)
        else:
            match = _ironpython26_sys_version_parser.match(sys_version)

1049 1050 1051 1052
        if match is None:
            raise ValueError(
                'failed to parse IronPython sys.version: %s' %
                repr(sys_version))
1053

1054 1055 1056 1057
        version, alt_version, compiler = match.groups()
        buildno = ''
        builddate = ''

1058
    elif sys.platform.startswith('java'):
1059 1060
        # Jython
        name = 'Jython'
Benjamin Peterson's avatar
Benjamin Peterson committed
1061
        match = _sys_version_parser.match(sys_version)
1062 1063 1064 1065
        if match is None:
            raise ValueError(
                'failed to parse Jython sys.version: %s' %
                repr(sys_version))
Benjamin Peterson's avatar
Benjamin Peterson committed
1066
        version, buildno, builddate, buildtime, _ = match.groups()
1067 1068
        if builddate is None:
            builddate = ''
1069
        compiler = sys.platform
Benjamin Peterson's avatar
Benjamin Peterson committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

    elif "PyPy" in sys_version:
        # PyPy
        name = "PyPy"
        match = _pypy_sys_version_parser.match(sys_version)
        if match is None:
            raise ValueError("failed to parse PyPy sys.version: %s" %
                             repr(sys_version))
        version, buildno, builddate, buildtime = match.groups()
        compiler = ""
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

    else:
        # CPython
        match = _sys_version_parser.match(sys_version)
        if match is None:
            raise ValueError(
                'failed to parse CPython sys.version: %s' %
                repr(sys_version))
        version, buildno, builddate, buildtime, compiler = \
              match.groups()
Benjamin Peterson's avatar
Benjamin Peterson committed
1090
        name = 'CPython'
1091 1092 1093 1094
        if builddate is None:
            builddate = ''
        elif buildtime:
            builddate = builddate + ' ' + buildtime
1095

1096 1097 1098
    if hasattr(sys, '_git'):
        _, branch, revision = sys._git
    elif hasattr(sys, '_mercurial'):
1099
        _, branch, revision = sys._mercurial
Benjamin Peterson's avatar
Benjamin Peterson committed
1100 1101 1102 1103
    else:
        branch = ''
        revision = ''

1104
    # Add the patchlevel version if missing
1105
    l = version.split('.')
1106 1107
    if len(l) == 2:
        l.append('0')
1108
        version = '.'.join(l)
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119

    # Build and cache the result
    result = (name, version, branch, revision, buildno, builddate, compiler)
    _sys_version_cache[sys_version] = result
    return result

def python_implementation():

    """ Returns a string identifying the Python implementation.

        Currently, the following implementations are identified:
1120 1121 1122 1123
          'CPython' (C implementation of Python),
          'IronPython' (.NET implementation of Python),
          'Jython' (Java implementation of Python),
          'PyPy' (Python implementation of Python).
1124 1125 1126

    """
    return _sys_version()[0]
1127 1128 1129 1130 1131 1132 1133 1134 1135

def python_version():

    """ Returns the Python version as string 'major.minor.patchlevel'

        Note that unlike the Python sys.version, the returned value
        will always include the patchlevel (it defaults to 0).

    """
1136
    return _sys_version()[1]
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

def python_version_tuple():

    """ Returns the Python version as tuple (major, minor, patchlevel)
        of strings.

        Note that unlike the Python sys.version, the returned value
        will always include the patchlevel (it defaults to 0).

    """
1147
    return tuple(_sys_version()[1].split('.'))
1148 1149 1150 1151 1152 1153

def python_branch():

    """ Returns a string identifying the Python implementation
        branch.

1154
        For CPython this is the SCM branch from which the
1155 1156 1157 1158 1159
        Python binary was built.

        If not available, an empty string is returned.

    """
1160

1161 1162 1163 1164 1165 1166 1167
    return _sys_version()[2]

def python_revision():

    """ Returns a string identifying the Python implementation
        revision.

1168
        For CPython this is the SCM revision from which the
1169 1170 1171 1172 1173 1174
        Python binary was built.

        If not available, an empty string is returned.

    """
    return _sys_version()[3]
1175 1176 1177 1178 1179 1180 1181

def python_build():

    """ Returns a tuple (buildno, builddate) stating the Python
        build number and date as strings.

    """
1182
    return _sys_version()[4:6]
1183 1184 1185 1186 1187 1188 1189

def python_compiler():

    """ Returns a string identifying the compiler used for compiling
        Python.

    """
1190
    return _sys_version()[6]
1191 1192 1193

### The Opus Magnum of platform strings :-)

1194
_platform_cache = {}
1195 1196 1197 1198 1199

def platform(aliased=0, terse=0):

    """ Returns a single string identifying the underlying platform
        with as much useful information as possible (but no more :).
Tim Peters's avatar
Tim Peters committed
1200

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
        The output is intended to be human readable rather than
        machine parseable. It may look different on different
        platforms and this is intended.

        If "aliased" is true, the function will use aliases for
        various platforms that report system names which differ from
        their common names, e.g. SunOS will be reported as
        Solaris. The system_alias() function is used to implement
        this.

        Setting terse to true causes the function to return only the
        absolute minimum information needed to identify the platform.

    """
1215 1216 1217
    result = _platform_cache.get((aliased, terse), None)
    if result is not None:
        return result
1218 1219 1220

    # Get uname information and then apply platform specific cosmetics
    # to it...
1221
    system, node, release, version, machine, processor = uname()
1222 1223 1224
    if machine == processor:
        processor = ''
    if aliased:
1225
        system, release, version = system_alias(system, release, version)
1226 1227 1228

    if system == 'Windows':
        # MS platforms
1229
        rel, vers, csd, ptype = win32_ver(version)
1230
        if terse:
1231
            platform = _platform(system, release)
1232
        else:
1233
            platform = _platform(system, release, version, csd)
1234 1235

    elif system in ('Linux',):
1236 1237 1238 1239 1240
        # check for libc vs. glibc
        libcname, libcversion = libc_ver(sys.executable)
        platform = _platform(system, release, machine, processor,
                             'with',
                             libcname+libcversion)
1241 1242
    elif system == 'Java':
        # Java platforms
1243
        r, v, vminfo, (os_name, os_version, os_arch) = java_ver()
1244
        if terse or not os_name:
1245
            platform = _platform(system, release, version)
1246
        else:
1247
            platform = _platform(system, release, version,
1248
                                 'on',
1249
                                 os_name, os_version, os_arch)
1250 1251 1252 1253

    elif system == 'MacOS':
        # MacOS platforms
        if terse:
1254
            platform = _platform(system, release)
1255
        else:
1256
            platform = _platform(system, release, machine)
1257 1258 1259 1260

    else:
        # Generic handler
        if terse:
1261
            platform = _platform(system, release)
1262
        else:
1263 1264 1265
            bits, linkage = architecture(sys.executable)
            platform = _platform(system, release, machine,
                                 processor, bits, linkage)
Tim Peters's avatar
Tim Peters committed
1266

1267
    _platform_cache[(aliased, terse)] = platform
1268 1269 1270 1271 1272 1273
    return platform

### Command line interface

if __name__ == '__main__':
    # Default is to print the aliased verbose platform string
Tim Peters's avatar
Tim Peters committed
1274
    terse = ('terse' in sys.argv or '--terse' in sys.argv)
1275
    aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
1276
    print(platform(aliased, terse))
1277
    sys.exit(0)