Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/platform.py

    r2 r391  
    3535#    <see CVS and SVN checkin messages for history>
    3636#
     37#    1.0.7 - added DEV_NULL
    3738#    1.0.6 - added linux_distribution()
    3839#    1.0.5 - fixed Java support to allow running the module on Jython
     
    9293__copyright__ = """
    9394    Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
    94     Copyright (c) 2000-2008, eGenix.com Software GmbH; mailto:info@egenix.com
     95    Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
    9596
    9697    Permission to use, copy, modify, and distribute this software and its
     
    111112"""
    112113
    113 __version__ = '1.0.6'
     114__version__ = '1.0.7'
    114115
    115116import sys,string,os,re
     117
     118### Globals & Constants
     119
     120# Determine the platform's /dev/null device
     121try:
     122    DEV_NULL = os.devnull
     123except AttributeError:
     124    # os.devnull was added in Python 2.4, so emulate it for earlier
     125    # Python versions
     126    if sys.platform in ('dos','win32','win16','os2'):
     127        # Use the old CP/M NUL as device name
     128        DEV_NULL = 'NUL'
     129    else:
     130        # Standard Unix uses /dev/null
     131        DEV_NULL = '/dev/null'
    116132
    117133### Platform specific APIs
     
    168184            if lib != 'glibc':
    169185                lib = 'libc'
    170                 if soversion > version:
     186                if soversion and soversion > version:
    171187                    version = soversion
    172188                if threads and version[-len(threads):] != threads:
     
    213229
    214230    if os.path.isdir('/usr/lib/setup'):
    215         # Check for slackware verson tag file (thanks to Greg Andruk)
     231        # Check for slackware version tag file (thanks to Greg Andruk)
    216232        verfiles = os.listdir('/usr/lib/setup')
    217233        for n in range(len(verfiles)-1, -1, -1):
     
    265281        return tuple(m.groups())
    266282
    267     # Unkown format... take the first two words
     283    # Unknown format... take the first two words
    268284    l = string.split(string.strip(firstline))
    269285    if l:
     
    272288            id = l[1]
    273289    return '', version, id
    274 
    275 def _test_parse_release_file():
    276 
    277     for input, output in (
    278         # Examples of release file contents:
    279         ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))
    280         ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))
    281         ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))
    282         ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))
    283         ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))
    284         ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))
    285         ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))
    286         ('CentOS release 4', ('CentOS', '4', None))
    287         ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia'))
    288         ):
    289         parsed = _parse_release_file(input)
    290         if parsed != output:
    291             print (input, parsed)
    292290
    293291def linux_distribution(distname='', version='', id='',
     
    471469_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
    472470                         '.*'
    473                          'Version ([\d.]+))')
     471                         '\[.* ([\d.]+)\])')
     472
     473# Examples of VER command output:
     474#
     475#   Windows 2000:  Microsoft Windows 2000 [Version 5.00.2195]
     476#   Windows XP:    Microsoft Windows XP [Version 5.1.2600]
     477#   Windows Vista: Microsoft Windows [Version 6.0.6002]
     478#
     479# Note that the "Version" string gets localized on different
     480# Windows versions.
    474481
    475482def _syscmd_ver(system='', release='', version='',
     
    497504            if pipe.close():
    498505                raise os.error,'command failed'
    499             # XXX How can I supress shell errors from being written
     506            # XXX How can I suppress shell errors from being written
    500507            #     to stderr ?
    501508        except os.error,why:
     
    548555    """ Get additional version information from the Windows Registry
    549556        and return a tuple (version,csd,ptype) referring to version
    550         number, CSD level and OS type (multi/single
     557        number, CSD level (service pack), and OS type (multi/single
    551558        processor).
    552559
     
    597604            VER_PLATFORM_WIN32_NT = 2
    598605            VER_NT_WORKSTATION = 1
     606            VER_NT_SERVER = 3
     607            REG_SZ = 1
    599608
    600609    # Find out the registry key and some general version infos
    601     maj,min,buildno,plat,csd = GetVersionEx()
     610    winver = GetVersionEx()
     611    maj,min,buildno,plat,csd = winver
    602612    version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
    603     if csd[:13] == 'Service Pack ':
    604         csd = 'SP' + csd[13:]
     613    if hasattr(winver, "service_pack"):
     614        if winver.service_pack != "":
     615            csd = 'SP%s' % winver.service_pack_major
     616    else:
     617        if csd[:13] == 'Service Pack ':
     618            csd = 'SP' + csd[13:]
     619
    605620    if plat == VER_PLATFORM_WIN32_WINDOWS:
    606621        regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
     
    617632        elif maj == 5:
    618633            release = '2000'
     634
    619635    elif plat == VER_PLATFORM_WIN32_NT:
    620636        regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
     
    631647                release = 'post2003'
    632648        elif maj == 6:
     649            if hasattr(winver, "product_type"):
     650                product_type = winver.product_type
     651            else:
     652                product_type = VER_NT_WORKSTATION
     653                # Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
     654                # or help from the registry, we cannot properly identify
     655                # non-workstation versions.
     656                try:
     657                    key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
     658                    name, type = RegQueryValueEx(key, "ProductName")
     659                    # Discard any type that isn't REG_SZ
     660                    if type == REG_SZ and name.find("Server") != -1:
     661                        product_type = VER_NT_SERVER
     662                except WindowsError:
     663                    # Use default of VER_NT_WORKSTATION
     664                    pass
     665
    633666            if min == 0:
    634                 # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx
    635                 try:
    636                     productType = GetVersionEx(1)[8]
    637                 except TypeError:
    638                     # sys.getwindowsversion() doesn't take any arguments, so
    639                     # we cannot detect 2008 Server that way.
    640                     # XXX Add some other means of detecting 2008 Server ?!
     667                if product_type == VER_NT_WORKSTATION:
    641668                    release = 'Vista'
    642669                else:
    643                     if productType == VER_NT_WORKSTATION:
    644                         release = 'Vista'
    645                     else:
    646                         release = '2008Server'
     670                    release = '2008Server'
     671            elif min == 1:
     672                if product_type == VER_NT_WORKSTATION:
     673                    release = '7'
     674                else:
     675                    release = '2008ServerR2'
     676            elif min == 2:
     677                if product_type == VER_NT_WORKSTATION:
     678                    release = '8'
     679                else:
     680                    release = '2012Server'
    647681            else:
    648                 release = 'post2008Server'
     682                release = 'post2012Server'
     683
    649684    else:
    650685        if not release:
     
    698733    return hex(bcd)[2:]
    699734
    700 def mac_ver(release='',versioninfo=('','',''),machine=''):
    701 
    702     """ Get MacOS version information and return it as tuple (release,
    703         versioninfo, machine) with versioninfo being a tuple (version,
    704         dev_stage, non_release_version).
    705 
    706         Entries which cannot be determined are set to the paramter values
    707         which default to ''. All tuple entries are strings.
    708 
     735def _mac_ver_gestalt():
     736    """
    709737        Thanks to Mark R. Levinson for mailing documentation links and
    710738        code examples for this function. Documentation for the
     
    712740
    713741           http://www.rgaros.nl/gestalt/
    714 
    715742    """
    716743    # Check whether the version info module is available
     
    719746        import MacOS
    720747    except ImportError:
    721         return release,versioninfo,machine
     748        return None
    722749    # Get the infos
    723750    sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
     
    743770                   0x2: 'PowerPC',
    744771                   0xa: 'i386'}.get(sysa,'')
     772
     773    versioninfo=('', '', '')
     774    return release,versioninfo,machine
     775
     776def _mac_ver_xml():
     777    fn = '/System/Library/CoreServices/SystemVersion.plist'
     778    if not os.path.exists(fn):
     779        return None
     780
     781    try:
     782        import plistlib
     783    except ImportError:
     784        return None
     785
     786    pl = plistlib.readPlist(fn)
     787    release = pl['ProductVersion']
     788    versioninfo=('', '', '')
     789    machine = os.uname()[4]
     790    if machine in ('ppc', 'Power Macintosh'):
     791        # for compatibility with the gestalt based code
     792        machine = 'PowerPC'
     793
     794    return release,versioninfo,machine
     795
     796
     797def mac_ver(release='',versioninfo=('','',''),machine=''):
     798
     799    """ Get MacOS version information and return it as tuple (release,
     800        versioninfo, machine) with versioninfo being a tuple (version,
     801        dev_stage, non_release_version).
     802
     803        Entries which cannot be determined are set to the parameter values
     804        which default to ''. All tuple entries are strings.
     805    """
     806
     807    # First try reading the information from an XML file which should
     808    # always be present
     809    info = _mac_ver_xml()
     810    if info is not None:
     811        return info
     812
     813    # If that doesn't work for some reason fall back to reading the
     814    # information using gestalt calls.
     815    info = _mac_ver_gestalt()
     816    if info is not None:
     817        return info
     818
     819    # If that also doesn't work return the default values
    745820    return release,versioninfo,machine
    746821
     
    9311006        return default
    9321007    try:
    933         f = os.popen('uname %s 2> /dev/null' % option)
     1008        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
    9341009    except (AttributeError,os.error):
    9351010        return default
     
    9511026
    9521027    """
     1028
     1029    # We do the import here to avoid a bootstrap issue.
     1030    # See c73b90b6dadd changeset.
     1031    #
     1032    # [..]
     1033    # ranlib libpython2.7.a
     1034    # gcc   -o python \
     1035    #        Modules/python.o \
     1036    #        libpython2.7.a -lsocket -lnsl -ldl    -lm
     1037    # Traceback (most recent call last):
     1038    #  File "./setup.py", line 8, in <module>
     1039    #    from platform import machine as platform_machine
     1040    #  File "[..]/build/Lib/platform.py", line 116, in <module>
     1041    #    import sys,string,os,re,subprocess
     1042    #  File "[..]/build/Lib/subprocess.py", line 429, in <module>
     1043    #    import select
     1044    # ImportError: No module named select
     1045
     1046    import subprocess
     1047
    9531048    if sys.platform in ('dos','win32','win16','os2'):
    9541049        # XXX Others too ?
     
    9561051    target = _follow_symlinks(target)
    9571052    try:
    958         f = os.popen('file "%s" 2> /dev/null' % target)
     1053        proc = subprocess.Popen(['file', target],
     1054                stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
     1055
    9591056    except (AttributeError,os.error):
    9601057        return default
    961     output = string.strip(f.read())
    962     rc = f.close()
     1058    output = proc.communicate()[0]
     1059    rc = proc.wait()
    9631060    if not output or rc:
    9641061        return default
     
    10201117        # "file" command did not return anything; we'll try to provide
    10211118        # some sensible defaults then...
    1022         if _default_architecture.has_key(sys.platform):
    1023             b,l = _default_architecture[sys.platform]
     1119        if sys.platform in _default_architecture:
     1120            b, l = _default_architecture[sys.platform]
    10241121            if b:
    10251122                bits = b
    10261123            if l:
    10271124                linkage = l
    1028         return bits,linkage
     1125        return bits, linkage
    10291126
    10301127    # Split the output into a list of strings omitting the filename
     
    11031200            machine = ''
    11041201
    1105         use_syscmd_ver = 01
     1202        use_syscmd_ver = 1
    11061203
    11071204        # Try win32_ver() on win32 platforms
     
    11151212            # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
    11161213            if not machine:
    1117                 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
     1214                # WOW64 processes mask the native architecture
     1215                if "PROCESSOR_ARCHITEW6432" in os.environ:
     1216                    machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
     1217                else:
     1218                    machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
    11181219            if not processor:
    11191220                processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
     
    11541255            if not version:
    11551256                version = vendor
    1156 
    1157         elif os.name == 'mac':
    1158             release,(version,stage,nonrel),machine = mac_ver()
    1159             system = 'MacOS'
    11601257
    11611258    # System specific extensions
     
    12691366    '\[([^\]]+)\]?')
    12701367
    1271 _jython_sys_version_parser = re.compile(
    1272     r'([\d\.]+)')
    1273 
    12741368_ironpython_sys_version_parser = re.compile(
    12751369    r'IronPython\s*'
     
    12781372    ' on (.NET [\d\.]+)')
    12791373
     1374# IronPython covering 2.6 and 2.7
     1375_ironpython26_sys_version_parser = re.compile(
     1376    r'([\d.]+)\s*'
     1377    '\(IronPython\s*'
     1378    '[\d.]+\s*'
     1379    '\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
     1380)
     1381
     1382_pypy_sys_version_parser = re.compile(
     1383    r'([\w.+]+)\s*'
     1384    '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
     1385    '\[PyPy [^\]]+\]?')
     1386
    12801387_sys_version_cache = {}
    12811388
     
    13101417
    13111418    # Parse it
    1312     if sys_version[:10] == 'IronPython':
     1419    if 'IronPython' in sys_version:
    13131420        # IronPython
    13141421        name = 'IronPython'
    1315         match = _ironpython_sys_version_parser.match(sys_version)
     1422        if sys_version.startswith('IronPython'):
     1423            match = _ironpython_sys_version_parser.match(sys_version)
     1424        else:
     1425            match = _ironpython26_sys_version_parser.match(sys_version)
     1426
    13161427        if match is None:
    13171428            raise ValueError(
    13181429                'failed to parse IronPython sys.version: %s' %
    13191430                repr(sys_version))
     1431
    13201432        version, alt_version, compiler = match.groups()
    1321         branch = ''
    1322         revision = ''
    13231433        buildno = ''
    13241434        builddate = ''
    13251435
    1326     elif sys.platform[:4] == 'java':
     1436    elif sys.platform.startswith('java'):
    13271437        # Jython
    13281438        name = 'Jython'
    1329         match = _jython_sys_version_parser.match(sys_version)
     1439        match = _sys_version_parser.match(sys_version)
    13301440        if match is None:
    13311441            raise ValueError(
    13321442                'failed to parse Jython sys.version: %s' %
    13331443                repr(sys_version))
    1334         version, = match.groups()
    1335         branch = ''
    1336         revision = ''
     1444        version, buildno, builddate, buildtime, _ = match.groups()
    13371445        compiler = sys.platform
    1338         buildno = ''
    1339         builddate = ''
     1446
     1447    elif "PyPy" in sys_version:
     1448        # PyPy
     1449        name = "PyPy"
     1450        match = _pypy_sys_version_parser.match(sys_version)
     1451        if match is None:
     1452            raise ValueError("failed to parse PyPy sys.version: %s" %
     1453                             repr(sys_version))
     1454        version, buildno, builddate, buildtime = match.groups()
     1455        compiler = ""
    13401456
    13411457    else:
     
    13481464        version, buildno, builddate, buildtime, compiler = \
    13491465              match.groups()
    1350         if hasattr(sys, 'subversion'):
    1351             # sys.subversion was added in Python 2.5
    1352             name, branch, revision = sys.subversion
    1353         else:
    1354             name = 'CPython'
    1355             branch = ''
    1356             revision = ''
     1466        name = 'CPython'
    13571467        builddate = builddate + ' ' + buildtime
     1468
     1469    if hasattr(sys, 'subversion'):
     1470        # sys.subversion was added in Python 2.5
     1471        _, branch, revision = sys.subversion
     1472    else:
     1473        branch = ''
     1474        revision = ''
    13581475
    13591476    # Add the patchlevel version if missing
     
    13681485    return result
    13691486
    1370 def _test_sys_version():
    1371 
    1372     _sys_version_cache.clear()
    1373     for input, output in (
    1374         ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
    1375          ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
    1376         ('IronPython 1.0.60816 on .NET 2.0.50727.42',
    1377          ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
    1378         ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
    1379          ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
    1380         ):
    1381         parsed = _sys_version(input)
    1382         if parsed != output:
    1383             print (input, parsed)
    1384 
    13851487def python_implementation():
    13861488
     
    13881490
    13891491        Currently, the following implementations are identified:
    1390         'CPython' (C implementation of Python),
    1391         'IronPython' (.NET implementation of Python),
    1392         'Jython' (Java implementation of Python).
     1492          'CPython' (C implementation of Python),
     1493          'IronPython' (.NET implementation of Python),
     1494          'Jython' (Java implementation of Python),
     1495          'PyPy' (Python implementation of Python).
    13931496
    13941497    """
Note: See TracChangeset for help on using the changeset viewer.