]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.10/Lib/platform.py
AppPkg/Applications/Python/Python-2.7.10: Initial Checkin part 4/5.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / Lib / platform.py
diff --git a/AppPkg/Applications/Python/Python-2.7.10/Lib/platform.py b/AppPkg/Applications/Python/Python-2.7.10/Lib/platform.py
new file mode 100644 (file)
index 0000000..8d7f1e7
--- /dev/null
@@ -0,0 +1,1655 @@
+#!/usr/bin/env python\r
+\r
+""" This module tries to retrieve as much platform-identifying data as\r
+    possible. It makes this information available via function APIs.\r
+\r
+    If called from the command line, it prints the platform\r
+    information concatenated as single string to stdout. The output\r
+    format is useable as part of a filename.\r
+\r
+"""\r
+#    This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.\r
+#    If you find problems, please submit bug reports/patches via the\r
+#    Python bug tracker (http://bugs.python.org) and assign them to "lemburg".\r
+#\r
+#    Note: Please keep this module compatible to Python 1.5.2.\r
+#\r
+#    Still needed:\r
+#    * more support for WinCE\r
+#    * support for MS-DOS (PythonDX ?)\r
+#    * support for Amiga and other still unsupported platforms running Python\r
+#    * support for additional Linux distributions\r
+#\r
+#    Many thanks to all those who helped adding platform-specific\r
+#    checks (in no particular order):\r
+#\r
+#      Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,\r
+#      Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef\r
+#      Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg\r
+#      Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark\r
+#      Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),\r
+#      Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter\r
+#\r
+#    History:\r
+#\r
+#    <see CVS and SVN checkin messages for history>\r
+#\r
+#    1.0.7 - added DEV_NULL\r
+#    1.0.6 - added linux_distribution()\r
+#    1.0.5 - fixed Java support to allow running the module on Jython\r
+#    1.0.4 - added IronPython support\r
+#    1.0.3 - added normalization of Windows system name\r
+#    1.0.2 - added more Windows support\r
+#    1.0.1 - reformatted to make doc.py happy\r
+#    1.0.0 - reformatted a bit and checked into Python CVS\r
+#    0.8.0 - added sys.version parser and various new access\r
+#            APIs (python_version(), python_compiler(), etc.)\r
+#    0.7.2 - fixed architecture() to use sizeof(pointer) where available\r
+#    0.7.1 - added support for Caldera OpenLinux\r
+#    0.7.0 - some fixes for WinCE; untabified the source file\r
+#    0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and\r
+#            vms_lib.getsyi() configured\r
+#    0.6.1 - added code to prevent 'uname -p' on platforms which are\r
+#            known not to support it\r
+#    0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;\r
+#            did some cleanup of the interfaces - some APIs have changed\r
+#    0.5.5 - fixed another type in the MacOS code... should have\r
+#            used more coffee today ;-)\r
+#    0.5.4 - fixed a few typos in the MacOS code\r
+#    0.5.3 - added experimental MacOS support; added better popen()\r
+#            workarounds in _syscmd_ver() -- still not 100% elegant\r
+#            though\r
+#    0.5.2 - fixed uname() to return '' instead of 'unknown' in all\r
+#            return values (the system uname command tends to return\r
+#            'unknown' instead of just leaving the field emtpy)\r
+#    0.5.1 - included code for slackware dist; added exception handlers\r
+#            to cover up situations where platforms don't have os.popen\r
+#            (e.g. Mac) or fail on socket.gethostname(); fixed libc\r
+#            detection RE\r
+#    0.5.0 - changed the API names referring to system commands to *syscmd*;\r
+#            added java_ver(); made syscmd_ver() a private\r
+#            API (was system_ver() in previous versions) -- use uname()\r
+#            instead; extended the win32_ver() to also return processor\r
+#            type information\r
+#    0.4.0 - added win32_ver() and modified the platform() output for WinXX\r
+#    0.3.4 - fixed a bug in _follow_symlinks()\r
+#    0.3.3 - fixed popen() and "file" command invokation bugs\r
+#    0.3.2 - added architecture() API and support for it in platform()\r
+#    0.3.1 - fixed syscmd_ver() RE to support Windows NT\r
+#    0.3.0 - added system alias support\r
+#    0.2.3 - removed 'wince' again... oh well.\r
+#    0.2.2 - added 'wince' to syscmd_ver() supported platforms\r
+#    0.2.1 - added cache logic and changed the platform string format\r
+#    0.2.0 - changed the API to use functions instead of module globals\r
+#            since some action take too long to be run on module import\r
+#    0.1.0 - first release\r
+#\r
+#    You can always get the latest version of this module at:\r
+#\r
+#             http://www.egenix.com/files/python/platform.py\r
+#\r
+#    If that URL should fail, try contacting the author.\r
+\r
+__copyright__ = """\r
+    Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com\r
+    Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com\r
+\r
+    Permission to use, copy, modify, and distribute this software and its\r
+    documentation for any purpose and without fee or royalty is hereby granted,\r
+    provided that the above copyright notice appear in all copies and that\r
+    both that copyright notice and this permission notice appear in\r
+    supporting documentation or portions thereof, including modifications,\r
+    that you make.\r
+\r
+    EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO\r
+    THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\r
+    FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,\r
+    INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING\r
+    FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\r
+    NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION\r
+    WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !\r
+\r
+"""\r
+\r
+__version__ = '1.0.7'\r
+\r
+import sys,string,os,re\r
+\r
+### Globals & Constants\r
+\r
+# Determine the platform's /dev/null device\r
+try:\r
+    DEV_NULL = os.devnull\r
+except AttributeError:\r
+    # os.devnull was added in Python 2.4, so emulate it for earlier\r
+    # Python versions\r
+    if sys.platform in ('dos','win32','win16','os2'):\r
+        # Use the old CP/M NUL as device name\r
+        DEV_NULL = 'NUL'\r
+    else:\r
+        # Standard Unix uses /dev/null\r
+        DEV_NULL = '/dev/null'\r
+\r
+### Platform specific APIs\r
+\r
+_libc_search = re.compile(r'(__libc_init)'\r
+                          '|'\r
+                          '(GLIBC_([0-9.]+))'\r
+                          '|'\r
+                          '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')\r
+\r
+def libc_ver(executable=sys.executable,lib='',version='',\r
+\r
+             chunksize=2048):\r
+\r
+    """ Tries to determine the libc version that the file executable\r
+        (which defaults to the Python interpreter) is linked against.\r
+\r
+        Returns a tuple of strings (lib,version) which default to the\r
+        given parameters in case the lookup fails.\r
+\r
+        Note that the function has intimate knowledge of how different\r
+        libc versions add symbols to the executable and thus is probably\r
+        only useable for executables compiled using gcc.\r
+\r
+        The file is read and scanned in chunks of chunksize bytes.\r
+\r
+    """\r
+    if hasattr(os.path, 'realpath'):\r
+        # Python 2.2 introduced os.path.realpath(); it is used\r
+        # here to work around problems with Cygwin not being\r
+        # able to open symlinks for reading\r
+        executable = os.path.realpath(executable)\r
+    f = open(executable,'rb')\r
+    binary = f.read(chunksize)\r
+    pos = 0\r
+    while 1:\r
+        m = _libc_search.search(binary,pos)\r
+        if not m:\r
+            binary = f.read(chunksize)\r
+            if not binary:\r
+                break\r
+            pos = 0\r
+            continue\r
+        libcinit,glibc,glibcversion,so,threads,soversion = m.groups()\r
+        if libcinit and not lib:\r
+            lib = 'libc'\r
+        elif glibc:\r
+            if lib != 'glibc':\r
+                lib = 'glibc'\r
+                version = glibcversion\r
+            elif glibcversion > version:\r
+                version = glibcversion\r
+        elif so:\r
+            if lib != 'glibc':\r
+                lib = 'libc'\r
+                if soversion and soversion > version:\r
+                    version = soversion\r
+                if threads and version[-len(threads):] != threads:\r
+                    version = version + threads\r
+        pos = m.end()\r
+    f.close()\r
+    return lib,version\r
+\r
+def _dist_try_harder(distname,version,id):\r
+\r
+    """ Tries some special tricks to get the distribution\r
+        information in case the default method fails.\r
+\r
+        Currently supports older SuSE Linux, Caldera OpenLinux and\r
+        Slackware Linux distributions.\r
+\r
+    """\r
+    if os.path.exists('/var/adm/inst-log/info'):\r
+        # SuSE Linux stores distribution information in that file\r
+        info = open('/var/adm/inst-log/info').readlines()\r
+        distname = 'SuSE'\r
+        for line in info:\r
+            tv = string.split(line)\r
+            if len(tv) == 2:\r
+                tag,value = tv\r
+            else:\r
+                continue\r
+            if tag == 'MIN_DIST_VERSION':\r
+                version = string.strip(value)\r
+            elif tag == 'DIST_IDENT':\r
+                values = string.split(value,'-')\r
+                id = values[2]\r
+        return distname,version,id\r
+\r
+    if os.path.exists('/etc/.installed'):\r
+        # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)\r
+        info = open('/etc/.installed').readlines()\r
+        for line in info:\r
+            pkg = string.split(line,'-')\r
+            if len(pkg) >= 2 and pkg[0] == 'OpenLinux':\r
+                # XXX does Caldera support non Intel platforms ? If yes,\r
+                #     where can we find the needed id ?\r
+                return 'OpenLinux',pkg[1],id\r
+\r
+    if os.path.isdir('/usr/lib/setup'):\r
+        # Check for slackware version tag file (thanks to Greg Andruk)\r
+        verfiles = os.listdir('/usr/lib/setup')\r
+        for n in range(len(verfiles)-1, -1, -1):\r
+            if verfiles[n][:14] != 'slack-version-':\r
+                del verfiles[n]\r
+        if verfiles:\r
+            verfiles.sort()\r
+            distname = 'slackware'\r
+            version = verfiles[-1][14:]\r
+            return distname,version,id\r
+\r
+    return distname,version,id\r
+\r
+_release_filename = re.compile(r'(\w+)[-_](release|version)')\r
+_lsb_release_version = re.compile(r'(.+)'\r
+                                   ' release '\r
+                                   '([\d.]+)'\r
+                                   '[^(]*(?:\((.+)\))?')\r
+_release_version = re.compile(r'([^0-9]+)'\r
+                               '(?: release )?'\r
+                               '([\d.]+)'\r
+                               '[^(]*(?:\((.+)\))?')\r
+\r
+# See also http://www.novell.com/coolsolutions/feature/11251.html\r
+# and http://linuxmafia.com/faq/Admin/release-files.html\r
+# and http://data.linux-ntfs.org/rpm/whichrpm\r
+# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html\r
+\r
+_supported_dists = (\r
+    'SuSE', 'debian', 'fedora', 'redhat', 'centos',\r
+    'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',\r
+    'UnitedLinux', 'turbolinux')\r
+\r
+def _parse_release_file(firstline):\r
+\r
+    # Default to empty 'version' and 'id' strings.  Both defaults are used\r
+    # when 'firstline' is empty.  'id' defaults to empty when an id can not\r
+    # be deduced.\r
+    version = ''\r
+    id = ''\r
+\r
+    # Parse the first line\r
+    m = _lsb_release_version.match(firstline)\r
+    if m is not None:\r
+        # LSB format: "distro release x.x (codename)"\r
+        return tuple(m.groups())\r
+\r
+    # Pre-LSB format: "distro x.x (codename)"\r
+    m = _release_version.match(firstline)\r
+    if m is not None:\r
+        return tuple(m.groups())\r
+\r
+    # Unknown format... take the first two words\r
+    l = string.split(string.strip(firstline))\r
+    if l:\r
+        version = l[0]\r
+        if len(l) > 1:\r
+            id = l[1]\r
+    return '', version, id\r
+\r
+def linux_distribution(distname='', version='', id='',\r
+\r
+                       supported_dists=_supported_dists,\r
+                       full_distribution_name=1):\r
+\r
+    """ Tries to determine the name of the Linux OS distribution name.\r
+\r
+        The function first looks for a distribution release file in\r
+        /etc and then reverts to _dist_try_harder() in case no\r
+        suitable files are found.\r
+\r
+        supported_dists may be given to define the set of Linux\r
+        distributions to look for. It defaults to a list of currently\r
+        supported Linux distributions identified by their release file\r
+        name.\r
+\r
+        If full_distribution_name is true (default), the full\r
+        distribution read from the OS is returned. Otherwise the short\r
+        name taken from supported_dists is used.\r
+\r
+        Returns a tuple (distname,version,id) which default to the\r
+        args given as parameters.\r
+\r
+    """\r
+    try:\r
+        etc = os.listdir('/etc')\r
+    except os.error:\r
+        # Probably not a Unix system\r
+        return distname,version,id\r
+    etc.sort()\r
+    for file in etc:\r
+        m = _release_filename.match(file)\r
+        if m is not None:\r
+            _distname,dummy = m.groups()\r
+            if _distname in supported_dists:\r
+                distname = _distname\r
+                break\r
+    else:\r
+        return _dist_try_harder(distname,version,id)\r
+\r
+    # Read the first line\r
+    f = open('/etc/'+file, 'r')\r
+    firstline = f.readline()\r
+    f.close()\r
+    _distname, _version, _id = _parse_release_file(firstline)\r
+\r
+    if _distname and full_distribution_name:\r
+        distname = _distname\r
+    if _version:\r
+        version = _version\r
+    if _id:\r
+        id = _id\r
+    return distname, version, id\r
+\r
+# To maintain backwards compatibility:\r
+\r
+def dist(distname='',version='',id='',\r
+\r
+         supported_dists=_supported_dists):\r
+\r
+    """ Tries to determine the name of the Linux OS distribution name.\r
+\r
+        The function first looks for a distribution release file in\r
+        /etc and then reverts to _dist_try_harder() in case no\r
+        suitable files are found.\r
+\r
+        Returns a tuple (distname,version,id) which default to the\r
+        args given as parameters.\r
+\r
+    """\r
+    return linux_distribution(distname, version, id,\r
+                              supported_dists=supported_dists,\r
+                              full_distribution_name=0)\r
+\r
+class _popen:\r
+\r
+    """ Fairly portable (alternative) popen implementation.\r
+\r
+        This is mostly needed in case os.popen() is not available, or\r
+        doesn't work as advertised, e.g. in Win9X GUI programs like\r
+        PythonWin or IDLE.\r
+\r
+        Writing to the pipe is currently not supported.\r
+\r
+    """\r
+    tmpfile = ''\r
+    pipe = None\r
+    bufsize = None\r
+    mode = 'r'\r
+\r
+    def __init__(self,cmd,mode='r',bufsize=None):\r
+\r
+        if mode != 'r':\r
+            raise ValueError,'popen()-emulation only supports read mode'\r
+        import tempfile\r
+        self.tmpfile = tmpfile = tempfile.mktemp()\r
+        os.system(cmd + ' > %s' % tmpfile)\r
+        self.pipe = open(tmpfile,'rb')\r
+        self.bufsize = bufsize\r
+        self.mode = mode\r
+\r
+    def read(self):\r
+\r
+        return self.pipe.read()\r
+\r
+    def readlines(self):\r
+\r
+        if self.bufsize is not None:\r
+            return self.pipe.readlines()\r
+\r
+    def close(self,\r
+\r
+              remove=os.unlink,error=os.error):\r
+\r
+        if self.pipe:\r
+            rc = self.pipe.close()\r
+        else:\r
+            rc = 255\r
+        if self.tmpfile:\r
+            try:\r
+                remove(self.tmpfile)\r
+            except error:\r
+                pass\r
+        return rc\r
+\r
+    # Alias\r
+    __del__ = close\r
+\r
+def popen(cmd, mode='r', bufsize=None):\r
+\r
+    """ Portable popen() interface.\r
+    """\r
+    # Find a working popen implementation preferring win32pipe.popen\r
+    # over os.popen over _popen\r
+    popen = None\r
+    if os.environ.get('OS','') == 'Windows_NT':\r
+        # On NT win32pipe should work; on Win9x it hangs due to bugs\r
+        # in the MS C lib (see MS KnowledgeBase article Q150956)\r
+        try:\r
+            import win32pipe\r
+        except ImportError:\r
+            pass\r
+        else:\r
+            popen = win32pipe.popen\r
+    if popen is None:\r
+        if hasattr(os,'popen'):\r
+            popen = os.popen\r
+            # Check whether it works... it doesn't in GUI programs\r
+            # on Windows platforms\r
+            if sys.platform == 'win32': # XXX Others too ?\r
+                try:\r
+                    popen('')\r
+                except os.error:\r
+                    popen = _popen\r
+        else:\r
+            popen = _popen\r
+    if bufsize is None:\r
+        return popen(cmd,mode)\r
+    else:\r
+        return popen(cmd,mode,bufsize)\r
+\r
+def _norm_version(version, build=''):\r
+\r
+    """ Normalize the version and build strings and return a single\r
+        version string using the format major.minor.build (or patchlevel).\r
+    """\r
+    l = string.split(version,'.')\r
+    if build:\r
+        l.append(build)\r
+    try:\r
+        ints = map(int,l)\r
+    except ValueError:\r
+        strings = l\r
+    else:\r
+        strings = map(str,ints)\r
+    version = string.join(strings[:3],'.')\r
+    return version\r
+\r
+_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '\r
+                         '.*'\r
+                         '\[.* ([\d.]+)\])')\r
+\r
+# Examples of VER command output:\r
+#\r
+#   Windows 2000:  Microsoft Windows 2000 [Version 5.00.2195]\r
+#   Windows XP:    Microsoft Windows XP [Version 5.1.2600]\r
+#   Windows Vista: Microsoft Windows [Version 6.0.6002]\r
+#\r
+# Note that the "Version" string gets localized on different\r
+# Windows versions.\r
+\r
+def _syscmd_ver(system='', release='', version='',\r
+\r
+               supported_platforms=('win32','win16','dos','os2')):\r
+\r
+    """ Tries to figure out the OS version used and returns\r
+        a tuple (system,release,version).\r
+\r
+        It uses the "ver" shell command for this which is known\r
+        to exists on Windows, DOS and OS/2. XXX Others too ?\r
+\r
+        In case this fails, the given parameters are used as\r
+        defaults.\r
+\r
+    """\r
+    if sys.platform not in supported_platforms:\r
+        return system,release,version\r
+\r
+    # Try some common cmd strings\r
+    for cmd in ('ver','command /c ver','cmd /c ver'):\r
+        try:\r
+            pipe = popen(cmd)\r
+            info = pipe.read()\r
+            if pipe.close():\r
+                raise os.error,'command failed'\r
+            # XXX How can I suppress shell errors from being written\r
+            #     to stderr ?\r
+        except os.error,why:\r
+            #print 'Command %s failed: %s' % (cmd,why)\r
+            continue\r
+        except IOError,why:\r
+            #print 'Command %s failed: %s' % (cmd,why)\r
+            continue\r
+        else:\r
+            break\r
+    else:\r
+        return system,release,version\r
+\r
+    # Parse the output\r
+    info = string.strip(info)\r
+    m = _ver_output.match(info)\r
+    if m is not None:\r
+        system,release,version = m.groups()\r
+        # Strip trailing dots from version and release\r
+        if release[-1] == '.':\r
+            release = release[:-1]\r
+        if version[-1] == '.':\r
+            version = version[:-1]\r
+        # Normalize the version and build strings (eliminating additional\r
+        # zeros)\r
+        version = _norm_version(version)\r
+    return system,release,version\r
+\r
+def _win32_getvalue(key,name,default=''):\r
+\r
+    """ Read a value for name from the registry key.\r
+\r
+        In case this fails, default is returned.\r
+\r
+    """\r
+    try:\r
+        # Use win32api if available\r
+        from win32api import RegQueryValueEx\r
+    except ImportError:\r
+        # On Python 2.0 and later, emulate using _winreg\r
+        import _winreg\r
+        RegQueryValueEx = _winreg.QueryValueEx\r
+    try:\r
+        return RegQueryValueEx(key,name)\r
+    except:\r
+        return default\r
+\r
+def win32_ver(release='',version='',csd='',ptype=''):\r
+\r
+    """ Get additional version information from the Windows Registry\r
+        and return a tuple (version,csd,ptype) referring to version\r
+        number, CSD level (service pack), and OS type (multi/single\r
+        processor).\r
+\r
+        As a hint: ptype returns 'Uniprocessor Free' on single\r
+        processor NT machines and 'Multiprocessor Free' on multi\r
+        processor machines. The 'Free' refers to the OS version being\r
+        free of debugging code. It could also state 'Checked' which\r
+        means the OS version uses debugging code, i.e. code that\r
+        checks arguments, ranges, etc. (Thomas Heller).\r
+\r
+        Note: this function works best with Mark Hammond's win32\r
+        package installed, but also on Python 2.3 and later. It\r
+        obviously only runs on Win32 compatible platforms.\r
+\r
+    """\r
+    # XXX Is there any way to find out the processor type on WinXX ?\r
+    # XXX Is win32 available on Windows CE ?\r
+    #\r
+    # Adapted from code posted by Karl Putland to comp.lang.python.\r
+    #\r
+    # The mappings between reg. values and release names can be found\r
+    # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp\r
+\r
+    # Import the needed APIs\r
+    try:\r
+        import win32api\r
+        from win32api import RegQueryValueEx, RegOpenKeyEx, \\r
+             RegCloseKey, GetVersionEx\r
+        from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \\r
+             VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION\r
+    except ImportError:\r
+        # Emulate the win32api module using Python APIs\r
+        try:\r
+            sys.getwindowsversion\r
+        except AttributeError:\r
+            # No emulation possible, so return the defaults...\r
+            return release,version,csd,ptype\r
+        else:\r
+            # Emulation using _winreg (added in Python 2.0) and\r
+            # sys.getwindowsversion() (added in Python 2.3)\r
+            import _winreg\r
+            GetVersionEx = sys.getwindowsversion\r
+            RegQueryValueEx = _winreg.QueryValueEx\r
+            RegOpenKeyEx = _winreg.OpenKeyEx\r
+            RegCloseKey = _winreg.CloseKey\r
+            HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE\r
+            VER_PLATFORM_WIN32_WINDOWS = 1\r
+            VER_PLATFORM_WIN32_NT = 2\r
+            VER_NT_WORKSTATION = 1\r
+            VER_NT_SERVER = 3\r
+            REG_SZ = 1\r
+\r
+    # Find out the registry key and some general version infos\r
+    winver = GetVersionEx()\r
+    maj,min,buildno,plat,csd = winver\r
+    version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)\r
+    if hasattr(winver, "service_pack"):\r
+        if winver.service_pack != "":\r
+            csd = 'SP%s' % winver.service_pack_major\r
+    else:\r
+        if csd[:13] == 'Service Pack ':\r
+            csd = 'SP' + csd[13:]\r
+\r
+    if plat == VER_PLATFORM_WIN32_WINDOWS:\r
+        regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'\r
+        # Try to guess the release name\r
+        if maj == 4:\r
+            if min == 0:\r
+                release = '95'\r
+            elif min == 10:\r
+                release = '98'\r
+            elif min == 90:\r
+                release = 'Me'\r
+            else:\r
+                release = 'postMe'\r
+        elif maj == 5:\r
+            release = '2000'\r
+\r
+    elif plat == VER_PLATFORM_WIN32_NT:\r
+        regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'\r
+        if maj <= 4:\r
+            release = 'NT'\r
+        elif maj == 5:\r
+            if min == 0:\r
+                release = '2000'\r
+            elif min == 1:\r
+                release = 'XP'\r
+            elif min == 2:\r
+                release = '2003Server'\r
+            else:\r
+                release = 'post2003'\r
+        elif maj == 6:\r
+            if hasattr(winver, "product_type"):\r
+                product_type = winver.product_type\r
+            else:\r
+                product_type = VER_NT_WORKSTATION\r
+                # Without an OSVERSIONINFOEX capable sys.getwindowsversion(),\r
+                # or help from the registry, we cannot properly identify\r
+                # non-workstation versions.\r
+                try:\r
+                    key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)\r
+                    name, type = RegQueryValueEx(key, "ProductName")\r
+                    # Discard any type that isn't REG_SZ\r
+                    if type == REG_SZ and name.find("Server") != -1:\r
+                        product_type = VER_NT_SERVER\r
+                except WindowsError:\r
+                    # Use default of VER_NT_WORKSTATION\r
+                    pass\r
+\r
+            if min == 0:\r
+                if product_type == VER_NT_WORKSTATION:\r
+                    release = 'Vista'\r
+                else:\r
+                    release = '2008Server'\r
+            elif min == 1:\r
+                if product_type == VER_NT_WORKSTATION:\r
+                    release = '7'\r
+                else:\r
+                    release = '2008ServerR2'\r
+            elif min == 2:\r
+                if product_type == VER_NT_WORKSTATION:\r
+                    release = '8'\r
+                else:\r
+                    release = '2012Server'\r
+            else:\r
+                release = 'post2012Server'\r
+\r
+    else:\r
+        if not release:\r
+            # E.g. Win3.1 with win32s\r
+            release = '%i.%i' % (maj,min)\r
+        return release,version,csd,ptype\r
+\r
+    # Open the registry key\r
+    try:\r
+        keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)\r
+        # Get a value to make sure the key exists...\r
+        RegQueryValueEx(keyCurVer, 'SystemRoot')\r
+    except:\r
+        return release,version,csd,ptype\r
+\r
+    # Parse values\r
+    #subversion = _win32_getvalue(keyCurVer,\r
+    #                            'SubVersionNumber',\r
+    #                            ('',1))[0]\r
+    #if subversion:\r
+    #   release = release + subversion # 95a, 95b, etc.\r
+    build = _win32_getvalue(keyCurVer,\r
+                            'CurrentBuildNumber',\r
+                            ('',1))[0]\r
+    ptype = _win32_getvalue(keyCurVer,\r
+                           'CurrentType',\r
+                           (ptype,1))[0]\r
+\r
+    # Normalize version\r
+    version = _norm_version(version,build)\r
+\r
+    # Close key\r
+    RegCloseKey(keyCurVer)\r
+    return release,version,csd,ptype\r
+\r
+def _mac_ver_lookup(selectors,default=None):\r
+\r
+    from gestalt import gestalt\r
+    import MacOS\r
+    l = []\r
+    append = l.append\r
+    for selector in selectors:\r
+        try:\r
+            append(gestalt(selector))\r
+        except (RuntimeError, MacOS.Error):\r
+            append(default)\r
+    return l\r
+\r
+def _bcd2str(bcd):\r
+\r
+    return hex(bcd)[2:]\r
+\r
+def _mac_ver_gestalt():\r
+    """\r
+        Thanks to Mark R. Levinson for mailing documentation links and\r
+        code examples for this function. Documentation for the\r
+        gestalt() API is available online at:\r
+\r
+           http://www.rgaros.nl/gestalt/\r
+    """\r
+    # Check whether the version info module is available\r
+    try:\r
+        import gestalt\r
+        import MacOS\r
+    except ImportError:\r
+        return None\r
+    # Get the infos\r
+    sysv,sysa = _mac_ver_lookup(('sysv','sysa'))\r
+    # Decode the infos\r
+    if sysv:\r
+        major = (sysv & 0xFF00) >> 8\r
+        minor = (sysv & 0x00F0) >> 4\r
+        patch = (sysv & 0x000F)\r
+\r
+        if (major, minor) >= (10, 4):\r
+            # the 'sysv' gestald cannot return patchlevels\r
+            # higher than 9. Apple introduced 3 new\r
+            # gestalt codes in 10.4 to deal with this\r
+            # issue (needed because patch levels can\r
+            # run higher than 9, such as 10.4.11)\r
+            major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))\r
+            release = '%i.%i.%i' %(major, minor, patch)\r
+        else:\r
+            release = '%s.%i.%i' % (_bcd2str(major),minor,patch)\r
+\r
+    if sysa:\r
+        machine = {0x1: '68k',\r
+                   0x2: 'PowerPC',\r
+                   0xa: 'i386'}.get(sysa,'')\r
+\r
+    versioninfo=('', '', '')\r
+    return release,versioninfo,machine\r
+\r
+def _mac_ver_xml():\r
+    fn = '/System/Library/CoreServices/SystemVersion.plist'\r
+    if not os.path.exists(fn):\r
+        return None\r
+\r
+    try:\r
+        import plistlib\r
+    except ImportError:\r
+        return None\r
+\r
+    pl = plistlib.readPlist(fn)\r
+    release = pl['ProductVersion']\r
+    versioninfo=('', '', '')\r
+    machine = os.uname()[4]\r
+    if machine in ('ppc', 'Power Macintosh'):\r
+        # for compatibility with the gestalt based code\r
+        machine = 'PowerPC'\r
+\r
+    return release,versioninfo,machine\r
+\r
+\r
+def mac_ver(release='',versioninfo=('','',''),machine=''):\r
+\r
+    """ Get MacOS version information and return it as tuple (release,\r
+        versioninfo, machine) with versioninfo being a tuple (version,\r
+        dev_stage, non_release_version).\r
+\r
+        Entries which cannot be determined are set to the parameter values\r
+        which default to ''. All tuple entries are strings.\r
+    """\r
+\r
+    # First try reading the information from an XML file which should\r
+    # always be present\r
+    info = _mac_ver_xml()\r
+    if info is not None:\r
+        return info\r
+\r
+    # If that doesn't work for some reason fall back to reading the\r
+    # information using gestalt calls.\r
+    info = _mac_ver_gestalt()\r
+    if info is not None:\r
+        return info\r
+\r
+    # If that also doesn't work return the default values\r
+    return release,versioninfo,machine\r
+\r
+def _java_getprop(name,default):\r
+\r
+    from java.lang import System\r
+    try:\r
+        value = System.getProperty(name)\r
+        if value is None:\r
+            return default\r
+        return value\r
+    except AttributeError:\r
+        return default\r
+\r
+def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):\r
+\r
+    """ Version interface for Jython.\r
+\r
+        Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being\r
+        a tuple (vm_name,vm_release,vm_vendor) and osinfo being a\r
+        tuple (os_name,os_version,os_arch).\r
+\r
+        Values which cannot be determined are set to the defaults\r
+        given as parameters (which all default to '').\r
+\r
+    """\r
+    # Import the needed APIs\r
+    try:\r
+        import java.lang\r
+    except ImportError:\r
+        return release,vendor,vminfo,osinfo\r
+\r
+    vendor = _java_getprop('java.vendor', vendor)\r
+    release = _java_getprop('java.version', release)\r
+    vm_name, vm_release, vm_vendor = vminfo\r
+    vm_name = _java_getprop('java.vm.name', vm_name)\r
+    vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)\r
+    vm_release = _java_getprop('java.vm.version', vm_release)\r
+    vminfo = vm_name, vm_release, vm_vendor\r
+    os_name, os_version, os_arch = osinfo\r
+    os_arch = _java_getprop('java.os.arch', os_arch)\r
+    os_name = _java_getprop('java.os.name', os_name)\r
+    os_version = _java_getprop('java.os.version', os_version)\r
+    osinfo = os_name, os_version, os_arch\r
+\r
+    return release, vendor, vminfo, osinfo\r
+\r
+### System name aliasing\r
+\r
+def system_alias(system,release,version):\r
+\r
+    """ Returns (system,release,version) aliased to common\r
+        marketing names used for some systems.\r
+\r
+        It also does some reordering of the information in some cases\r
+        where it would otherwise cause confusion.\r
+\r
+    """\r
+    if system == 'Rhapsody':\r
+        # Apple's BSD derivative\r
+        # XXX How can we determine the marketing release number ?\r
+        return 'MacOS X Server',system+release,version\r
+\r
+    elif system == 'SunOS':\r
+        # Sun's OS\r
+        if release < '5':\r
+            # These releases use the old name SunOS\r
+            return system,release,version\r
+        # Modify release (marketing release = SunOS release - 3)\r
+        l = string.split(release,'.')\r
+        if l:\r
+            try:\r
+                major = int(l[0])\r
+            except ValueError:\r
+                pass\r
+            else:\r
+                major = major - 3\r
+                l[0] = str(major)\r
+                release = string.join(l,'.')\r
+        if release < '6':\r
+            system = 'Solaris'\r
+        else:\r
+            # XXX Whatever the new SunOS marketing name is...\r
+            system = 'Solaris'\r
+\r
+    elif system == 'IRIX64':\r
+        # IRIX reports IRIX64 on platforms with 64-bit support; yet it\r
+        # is really a version and not a different platform, since 32-bit\r
+        # apps are also supported..\r
+        system = 'IRIX'\r
+        if version:\r
+            version = version + ' (64bit)'\r
+        else:\r
+            version = '64bit'\r
+\r
+    elif system in ('win32','win16'):\r
+        # In case one of the other tricks\r
+        system = 'Windows'\r
+\r
+    return system,release,version\r
+\r
+### Various internal helpers\r
+\r
+def _platform(*args):\r
+\r
+    """ Helper to format the platform string in a filename\r
+        compatible format e.g. "system-version-machine".\r
+    """\r
+    # Format the platform string\r
+    platform = string.join(\r
+        map(string.strip,\r
+            filter(len, args)),\r
+        '-')\r
+\r
+    # Cleanup some possible filename obstacles...\r
+    replace = string.replace\r
+    platform = replace(platform,' ','_')\r
+    platform = replace(platform,'/','-')\r
+    platform = replace(platform,'\\','-')\r
+    platform = replace(platform,':','-')\r
+    platform = replace(platform,';','-')\r
+    platform = replace(platform,'"','-')\r
+    platform = replace(platform,'(','-')\r
+    platform = replace(platform,')','-')\r
+\r
+    # No need to report 'unknown' information...\r
+    platform = replace(platform,'unknown','')\r
+\r
+    # Fold '--'s and remove trailing '-'\r
+    while 1:\r
+        cleaned = replace(platform,'--','-')\r
+        if cleaned == platform:\r
+            break\r
+        platform = cleaned\r
+    while platform[-1] == '-':\r
+        platform = platform[:-1]\r
+\r
+    return platform\r
+\r
+def _node(default=''):\r
+\r
+    """ Helper to determine the node name of this machine.\r
+    """\r
+    try:\r
+        import socket\r
+    except ImportError:\r
+        # No sockets...\r
+        return default\r
+    try:\r
+        return socket.gethostname()\r
+    except socket.error:\r
+        # Still not working...\r
+        return default\r
+\r
+# os.path.abspath is new in Python 1.5.2:\r
+if not hasattr(os.path,'abspath'):\r
+\r
+    def _abspath(path,\r
+\r
+                 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,\r
+                 normpath=os.path.normpath):\r
+\r
+        if not isabs(path):\r
+            path = join(getcwd(), path)\r
+        return normpath(path)\r
+\r
+else:\r
+\r
+    _abspath = os.path.abspath\r
+\r
+def _follow_symlinks(filepath):\r
+\r
+    """ In case filepath is a symlink, follow it until a\r
+        real file is reached.\r
+    """\r
+    filepath = _abspath(filepath)\r
+    while os.path.islink(filepath):\r
+        filepath = os.path.normpath(\r
+            os.path.join(os.path.dirname(filepath),os.readlink(filepath)))\r
+    return filepath\r
+\r
+def _syscmd_uname(option,default=''):\r
+\r
+    """ Interface to the system's uname command.\r
+    """\r
+    if sys.platform in ('dos','win32','win16','os2'):\r
+        # XXX Others too ?\r
+        return default\r
+    try:\r
+        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))\r
+    except (AttributeError,os.error):\r
+        return default\r
+    output = string.strip(f.read())\r
+    rc = f.close()\r
+    if not output or rc:\r
+        return default\r
+    else:\r
+        return output\r
+\r
+def _syscmd_file(target,default=''):\r
+\r
+    """ Interface to the system's file command.\r
+\r
+        The function uses the -b option of the file command to have it\r
+        ommit the filename in its output and if possible the -L option\r
+        to have the command follow symlinks. It returns default in\r
+        case the command should fail.\r
+\r
+    """\r
+\r
+    # We do the import here to avoid a bootstrap issue.\r
+    # See c73b90b6dadd changeset.\r
+    #\r
+    # [..]\r
+    # ranlib libpython2.7.a\r
+    # gcc   -o python \\r
+    #        Modules/python.o \\r
+    #        libpython2.7.a -lsocket -lnsl -ldl    -lm\r
+    # Traceback (most recent call last):\r
+    #  File "./setup.py", line 8, in <module>\r
+    #    from platform import machine as platform_machine\r
+    #  File "[..]/build/Lib/platform.py", line 116, in <module>\r
+    #    import sys,string,os,re,subprocess\r
+    #  File "[..]/build/Lib/subprocess.py", line 429, in <module>\r
+    #    import select\r
+    # ImportError: No module named select\r
+\r
+    import subprocess\r
+\r
+    if sys.platform in ('dos','win32','win16','os2'):\r
+        # XXX Others too ?\r
+        return default\r
+    target = _follow_symlinks(target)\r
+    try:\r
+        proc = subprocess.Popen(['file', target],\r
+                stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\r
+\r
+    except (AttributeError,os.error):\r
+        return default\r
+    output = proc.communicate()[0]\r
+    rc = proc.wait()\r
+    if not output or rc:\r
+        return default\r
+    else:\r
+        return output\r
+\r
+### Information about the used architecture\r
+\r
+# Default values for architecture; non-empty strings override the\r
+# defaults given as parameters\r
+_default_architecture = {\r
+    'win32': ('','WindowsPE'),\r
+    'win16': ('','Windows'),\r
+    'dos': ('','MSDOS'),\r
+}\r
+\r
+_architecture_split = re.compile(r'[\s,]').split\r
+\r
+def architecture(executable=sys.executable,bits='',linkage=''):\r
+\r
+    """ Queries the given executable (defaults to the Python interpreter\r
+        binary) for various architecture information.\r
+\r
+        Returns a tuple (bits,linkage) which contains information about\r
+        the bit architecture and the linkage format used for the\r
+        executable. Both values are returned as strings.\r
+\r
+        Values that cannot be determined are returned as given by the\r
+        parameter presets. If bits is given as '', the sizeof(pointer)\r
+        (or sizeof(long) on Python version < 1.5.2) is used as\r
+        indicator for the supported pointer size.\r
+\r
+        The function relies on the system's "file" command to do the\r
+        actual work. This is available on most if not all Unix\r
+        platforms. On some non-Unix platforms where the "file" command\r
+        does not exist and the executable is set to the Python interpreter\r
+        binary defaults from _default_architecture are used.\r
+\r
+    """\r
+    # Use the sizeof(pointer) as default number of bits if nothing\r
+    # else is given as default.\r
+    if not bits:\r
+        import struct\r
+        try:\r
+            size = struct.calcsize('P')\r
+        except struct.error:\r
+            # Older installations can only query longs\r
+            size = struct.calcsize('l')\r
+        bits = str(size*8) + 'bit'\r
+\r
+    # Get data from the 'file' system command\r
+    if executable:\r
+        output = _syscmd_file(executable, '')\r
+    else:\r
+        output = ''\r
+\r
+    if not output and \\r
+       executable == sys.executable:\r
+        # "file" command did not return anything; we'll try to provide\r
+        # some sensible defaults then...\r
+        if sys.platform in _default_architecture:\r
+            b, l = _default_architecture[sys.platform]\r
+            if b:\r
+                bits = b\r
+            if l:\r
+                linkage = l\r
+        return bits, linkage\r
+\r
+    # Split the output into a list of strings omitting the filename\r
+    fileout = _architecture_split(output)[1:]\r
+\r
+    if 'executable' not in fileout:\r
+        # Format not supported\r
+        return bits,linkage\r
+\r
+    # Bits\r
+    if '32-bit' in fileout:\r
+        bits = '32bit'\r
+    elif 'N32' in fileout:\r
+        # On Irix only\r
+        bits = 'n32bit'\r
+    elif '64-bit' in fileout:\r
+        bits = '64bit'\r
+\r
+    # Linkage\r
+    if 'ELF' in fileout:\r
+        linkage = 'ELF'\r
+    elif 'PE' in fileout:\r
+        # E.g. Windows uses this format\r
+        if 'Windows' in fileout:\r
+            linkage = 'WindowsPE'\r
+        else:\r
+            linkage = 'PE'\r
+    elif 'COFF' in fileout:\r
+        linkage = 'COFF'\r
+    elif 'MS-DOS' in fileout:\r
+        linkage = 'MSDOS'\r
+    else:\r
+        # XXX the A.OUT format also falls under this class...\r
+        pass\r
+\r
+    return bits,linkage\r
+\r
+### Portable uname() interface\r
+\r
+_uname_cache = None\r
+\r
+def uname():\r
+\r
+    """ Fairly portable uname interface. Returns a tuple\r
+        of strings (system,node,release,version,machine,processor)\r
+        identifying the underlying platform.\r
+\r
+        Note that unlike the os.uname function this also returns\r
+        possible processor information as an additional tuple entry.\r
+\r
+        Entries which cannot be determined are set to ''.\r
+\r
+    """\r
+    global _uname_cache\r
+    no_os_uname = 0\r
+\r
+    if _uname_cache is not None:\r
+        return _uname_cache\r
+\r
+    processor = ''\r
+\r
+    # Get some infos from the builtin os.uname API...\r
+    try:\r
+        system,node,release,version,machine = os.uname()\r
+    except AttributeError:\r
+        no_os_uname = 1\r
+\r
+    if no_os_uname or not filter(None, (system, node, release, version, machine)):\r
+        # Hmm, no there is either no uname or uname has returned\r
+        #'unknowns'... we'll have to poke around the system then.\r
+        if no_os_uname:\r
+            system = sys.platform\r
+            release = ''\r
+            version = ''\r
+            node = _node()\r
+            machine = ''\r
+\r
+        use_syscmd_ver = 1\r
+\r
+        # Try win32_ver() on win32 platforms\r
+        if system == 'win32':\r
+            release,version,csd,ptype = win32_ver()\r
+            if release and version:\r
+                use_syscmd_ver = 0\r
+            # Try to use the PROCESSOR_* environment variables\r
+            # available on Win XP and later; see\r
+            # http://support.microsoft.com/kb/888731 and\r
+            # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM\r
+            if not machine:\r
+                # WOW64 processes mask the native architecture\r
+                if "PROCESSOR_ARCHITEW6432" in os.environ:\r
+                    machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')\r
+                else:\r
+                    machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')\r
+            if not processor:\r
+                processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)\r
+\r
+        # Try the 'ver' system command available on some\r
+        # platforms\r
+        if use_syscmd_ver:\r
+            system,release,version = _syscmd_ver(system)\r
+            # Normalize system to what win32_ver() normally returns\r
+            # (_syscmd_ver() tends to return the vendor name as well)\r
+            if system == 'Microsoft Windows':\r
+                system = 'Windows'\r
+            elif system == 'Microsoft' and release == 'Windows':\r
+                # Under Windows Vista and Windows Server 2008,\r
+                # Microsoft changed the output of the ver command. The\r
+                # release is no longer printed.  This causes the\r
+                # system and release to be misidentified.\r
+                system = 'Windows'\r
+                if '6.0' == version[:3]:\r
+                    release = 'Vista'\r
+                else:\r
+                    release = ''\r
+\r
+        # In case we still don't know anything useful, we'll try to\r
+        # help ourselves\r
+        if system in ('win32','win16'):\r
+            if not version:\r
+                if system == 'win32':\r
+                    version = '32bit'\r
+                else:\r
+                    version = '16bit'\r
+            system = 'Windows'\r
+\r
+        elif system[:4] == 'java':\r
+            release,vendor,vminfo,osinfo = java_ver()\r
+            system = 'Java'\r
+            version = string.join(vminfo,', ')\r
+            if not version:\r
+                version = vendor\r
+\r
+    # System specific extensions\r
+    if system == 'OpenVMS':\r
+        # OpenVMS seems to have release and version mixed up\r
+        if not release or release == '0':\r
+            release = version\r
+            version = ''\r
+        # Get processor information\r
+        try:\r
+            import vms_lib\r
+        except ImportError:\r
+            pass\r
+        else:\r
+            csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)\r
+            if (cpu_number >= 128):\r
+                processor = 'Alpha'\r
+            else:\r
+                processor = 'VAX'\r
+    if not processor:\r
+        # Get processor information from the uname system command\r
+        processor = _syscmd_uname('-p','')\r
+\r
+    #If any unknowns still exist, replace them with ''s, which are more portable\r
+    if system == 'unknown':\r
+        system = ''\r
+    if node == 'unknown':\r
+        node = ''\r
+    if release == 'unknown':\r
+        release = ''\r
+    if version == 'unknown':\r
+        version = ''\r
+    if machine == 'unknown':\r
+        machine = ''\r
+    if processor == 'unknown':\r
+        processor = ''\r
+\r
+    #  normalize name\r
+    if system == 'Microsoft' and release == 'Windows':\r
+        system = 'Windows'\r
+        release = 'Vista'\r
+\r
+    _uname_cache = system,node,release,version,machine,processor\r
+    return _uname_cache\r
+\r
+### Direct interfaces to some of the uname() return values\r
+\r
+def system():\r
+\r
+    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.\r
+\r
+        An empty string is returned if the value cannot be determined.\r
+\r
+    """\r
+    return uname()[0]\r
+\r
+def node():\r
+\r
+    """ Returns the computer's network name (which may not be fully\r
+        qualified)\r
+\r
+        An empty string is returned if the value cannot be determined.\r
+\r
+    """\r
+    return uname()[1]\r
+\r
+def release():\r
+\r
+    """ Returns the system's release, e.g. '2.2.0' or 'NT'\r
+\r
+        An empty string is returned if the value cannot be determined.\r
+\r
+    """\r
+    return uname()[2]\r
+\r
+def version():\r
+\r
+    """ Returns the system's release version, e.g. '#3 on degas'\r
+\r
+        An empty string is returned if the value cannot be determined.\r
+\r
+    """\r
+    return uname()[3]\r
+\r
+def machine():\r
+\r
+    """ Returns the machine type, e.g. 'i386'\r
+\r
+        An empty string is returned if the value cannot be determined.\r
+\r
+    """\r
+    return uname()[4]\r
+\r
+def processor():\r
+\r
+    """ Returns the (true) processor name, e.g. 'amdk6'\r
+\r
+        An empty string is returned if the value cannot be\r
+        determined. Note that many platforms do not provide this\r
+        information or simply return the same value as for machine(),\r
+        e.g.  NetBSD does this.\r
+\r
+    """\r
+    return uname()[5]\r
+\r
+### Various APIs for extracting information from sys.version\r
+\r
+_sys_version_parser = re.compile(\r
+    r'([\w.+]+)\s*'\r
+    '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'\r
+    '\[([^\]]+)\]?')\r
+\r
+_ironpython_sys_version_parser = re.compile(\r
+    r'IronPython\s*'\r
+    '([\d\.]+)'\r
+    '(?: \(([\d\.]+)\))?'\r
+    ' on (.NET [\d\.]+)')\r
+\r
+# IronPython covering 2.6 and 2.7\r
+_ironpython26_sys_version_parser = re.compile(\r
+    r'([\d.]+)\s*'\r
+    '\(IronPython\s*'\r
+    '[\d.]+\s*'\r
+    '\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'\r
+)\r
+\r
+_pypy_sys_version_parser = re.compile(\r
+    r'([\w.+]+)\s*'\r
+    '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'\r
+    '\[PyPy [^\]]+\]?')\r
+\r
+_sys_version_cache = {}\r
+\r
+def _sys_version(sys_version=None):\r
+\r
+    """ Returns a parsed version of Python's sys.version as tuple\r
+        (name, version, branch, revision, buildno, builddate, compiler)\r
+        referring to the Python implementation name, version, branch,\r
+        revision, build number, build date/time as string and the compiler\r
+        identification string.\r
+\r
+        Note that unlike the Python sys.version, the returned value\r
+        for the Python version will always include the patchlevel (it\r
+        defaults to '.0').\r
+\r
+        The function returns empty strings for tuple entries that\r
+        cannot be determined.\r
+\r
+        sys_version may be given to parse an alternative version\r
+        string, e.g. if the version was read from a different Python\r
+        interpreter.\r
+\r
+    """\r
+    # Get the Python version\r
+    if sys_version is None:\r
+        sys_version = sys.version\r
+\r
+    # Try the cache first\r
+    result = _sys_version_cache.get(sys_version, None)\r
+    if result is not None:\r
+        return result\r
+\r
+    # Parse it\r
+    if 'IronPython' in sys_version:\r
+        # IronPython\r
+        name = 'IronPython'\r
+        if sys_version.startswith('IronPython'):\r
+            match = _ironpython_sys_version_parser.match(sys_version)\r
+        else:\r
+            match = _ironpython26_sys_version_parser.match(sys_version)\r
+\r
+        if match is None:\r
+            raise ValueError(\r
+                'failed to parse IronPython sys.version: %s' %\r
+                repr(sys_version))\r
+\r
+        version, alt_version, compiler = match.groups()\r
+        buildno = ''\r
+        builddate = ''\r
+\r
+    elif sys.platform.startswith('java'):\r
+        # Jython\r
+        name = 'Jython'\r
+        match = _sys_version_parser.match(sys_version)\r
+        if match is None:\r
+            raise ValueError(\r
+                'failed to parse Jython sys.version: %s' %\r
+                repr(sys_version))\r
+        version, buildno, builddate, buildtime, _ = match.groups()\r
+        compiler = sys.platform\r
+\r
+    elif "PyPy" in sys_version:\r
+        # PyPy\r
+        name = "PyPy"\r
+        match = _pypy_sys_version_parser.match(sys_version)\r
+        if match is None:\r
+            raise ValueError("failed to parse PyPy sys.version: %s" %\r
+                             repr(sys_version))\r
+        version, buildno, builddate, buildtime = match.groups()\r
+        compiler = ""\r
+\r
+    else:\r
+        # CPython\r
+        match = _sys_version_parser.match(sys_version)\r
+        if match is None:\r
+            raise ValueError(\r
+                'failed to parse CPython sys.version: %s' %\r
+                repr(sys_version))\r
+        version, buildno, builddate, buildtime, compiler = \\r
+              match.groups()\r
+        name = 'CPython'\r
+        builddate = builddate + ' ' + buildtime\r
+\r
+    if hasattr(sys, 'subversion'):\r
+        # sys.subversion was added in Python 2.5\r
+        _, branch, revision = sys.subversion\r
+    else:\r
+        branch = ''\r
+        revision = ''\r
+\r
+    # Add the patchlevel version if missing\r
+    l = string.split(version, '.')\r
+    if len(l) == 2:\r
+        l.append('0')\r
+        version = string.join(l, '.')\r
+\r
+    # Build and cache the result\r
+    result = (name, version, branch, revision, buildno, builddate, compiler)\r
+    _sys_version_cache[sys_version] = result\r
+    return result\r
+\r
+def python_implementation():\r
+\r
+    """ Returns a string identifying the Python implementation.\r
+\r
+        Currently, the following implementations are identified:\r
+          'CPython' (C implementation of Python),\r
+          'IronPython' (.NET implementation of Python),\r
+          'Jython' (Java implementation of Python),\r
+          'PyPy' (Python implementation of Python).\r
+\r
+    """\r
+    return _sys_version()[0]\r
+\r
+def python_version():\r
+\r
+    """ Returns the Python version as string 'major.minor.patchlevel'\r
+\r
+        Note that unlike the Python sys.version, the returned value\r
+        will always include the patchlevel (it defaults to 0).\r
+\r
+    """\r
+    return _sys_version()[1]\r
+\r
+def python_version_tuple():\r
+\r
+    """ Returns the Python version as tuple (major, minor, patchlevel)\r
+        of strings.\r
+\r
+        Note that unlike the Python sys.version, the returned value\r
+        will always include the patchlevel (it defaults to 0).\r
+\r
+    """\r
+    return tuple(string.split(_sys_version()[1], '.'))\r
+\r
+def python_branch():\r
+\r
+    """ Returns a string identifying the Python implementation\r
+        branch.\r
+\r
+        For CPython this is the Subversion branch from which the\r
+        Python binary was built.\r
+\r
+        If not available, an empty string is returned.\r
+\r
+    """\r
+\r
+    return _sys_version()[2]\r
+\r
+def python_revision():\r
+\r
+    """ Returns a string identifying the Python implementation\r
+        revision.\r
+\r
+        For CPython this is the Subversion revision from which the\r
+        Python binary was built.\r
+\r
+        If not available, an empty string is returned.\r
+\r
+    """\r
+    return _sys_version()[3]\r
+\r
+def python_build():\r
+\r
+    """ Returns a tuple (buildno, builddate) stating the Python\r
+        build number and date as strings.\r
+\r
+    """\r
+    return _sys_version()[4:6]\r
+\r
+def python_compiler():\r
+\r
+    """ Returns a string identifying the compiler used for compiling\r
+        Python.\r
+\r
+    """\r
+    return _sys_version()[6]\r
+\r
+### The Opus Magnum of platform strings :-)\r
+\r
+_platform_cache = {}\r
+\r
+def platform(aliased=0, terse=0):\r
+\r
+    """ Returns a single string identifying the underlying platform\r
+        with as much useful information as possible (but no more :).\r
+\r
+        The output is intended to be human readable rather than\r
+        machine parseable. It may look different on different\r
+        platforms and this is intended.\r
+\r
+        If "aliased" is true, the function will use aliases for\r
+        various platforms that report system names which differ from\r
+        their common names, e.g. SunOS will be reported as\r
+        Solaris. The system_alias() function is used to implement\r
+        this.\r
+\r
+        Setting terse to true causes the function to return only the\r
+        absolute minimum information needed to identify the platform.\r
+\r
+    """\r
+    result = _platform_cache.get((aliased, terse), None)\r
+    if result is not None:\r
+        return result\r
+\r
+    # Get uname information and then apply platform specific cosmetics\r
+    # to it...\r
+    system,node,release,version,machine,processor = uname()\r
+    if machine == processor:\r
+        processor = ''\r
+    if aliased:\r
+        system,release,version = system_alias(system,release,version)\r
+\r
+    if system == 'Windows':\r
+        # MS platforms\r
+        rel,vers,csd,ptype = win32_ver(version)\r
+        if terse:\r
+            platform = _platform(system,release)\r
+        else:\r
+            platform = _platform(system,release,version,csd)\r
+\r
+    elif system in ('Linux',):\r
+        # Linux based systems\r
+        distname,distversion,distid = dist('')\r
+        if distname and not terse:\r
+            platform = _platform(system,release,machine,processor,\r
+                                 'with',\r
+                                 distname,distversion,distid)\r
+        else:\r
+            # If the distribution name is unknown check for libc vs. glibc\r
+            libcname,libcversion = libc_ver(sys.executable)\r
+            platform = _platform(system,release,machine,processor,\r
+                                 'with',\r
+                                 libcname+libcversion)\r
+    elif system == 'Java':\r
+        # Java platforms\r
+        r,v,vminfo,(os_name,os_version,os_arch) = java_ver()\r
+        if terse or not os_name:\r
+            platform = _platform(system,release,version)\r
+        else:\r
+            platform = _platform(system,release,version,\r
+                                 'on',\r
+                                 os_name,os_version,os_arch)\r
+\r
+    elif system == 'MacOS':\r
+        # MacOS platforms\r
+        if terse:\r
+            platform = _platform(system,release)\r
+        else:\r
+            platform = _platform(system,release,machine)\r
+\r
+    else:\r
+        # Generic handler\r
+        if terse:\r
+            platform = _platform(system,release)\r
+        else:\r
+            bits,linkage = architecture(sys.executable)\r
+            platform = _platform(system,release,machine,processor,bits,linkage)\r
+\r
+    _platform_cache[(aliased, terse)] = platform\r
+    return platform\r
+\r
+### Command line interface\r
+\r
+if __name__ == '__main__':\r
+    # Default is to print the aliased verbose platform string\r
+    terse = ('terse' in sys.argv or '--terse' in sys.argv)\r
+    aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)\r
+    print platform(aliased,terse)\r
+    sys.exit(0)\r