1254 lines · 39.4 KB · Python
RawDownload
#!/usr/bin/env python """ This module tries to retrieve as much platform-identifying data as    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#    Python SourceForge Project Page and assign them to "lemburg".##    Note: Please keep this module compatible to Python 1.5.2.##    Still needed:#    * more support for WinCE#    * support for MS-DOS (PythonDX ?)#    * support for Amiga and other still unsupported platforms running Python#    * support for additional Linux distributions##    Many thanks to all those who helped adding platform-specific#    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),#      Colin Kong, Trent Mick, Guido van Rossum##    History:##    <see CVS and SVN checkin messages for history>##    1.0.3 - added normalization of Windows system name#    1.0.2 - added more Windows support#    1.0.1 - reformatted to make doc.py happy#    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#            'unknown' instead of just leaving the field emtpy)#    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    Copyright (c) 2000-2003, eGenix.com Software GmbH; mailto:info@egenix.com     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 ! """ __version__ = '1.0.4' import sys,string,os,re ### Platform specific APIs _libc_search = re.compile(r'(__libc_init)'                          '|'                          '(GLIBC_([0-9.]+))'                          '|'                          '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)') def libc_ver(executable=sys.executable,lib='',version='',              chunksize=2048):     """ Tries to determine the libc version that the file executable        (which defaults to the Python interpreter) is linked against.         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        libc versions add symbols to the executable and thus is probably        only useable for executables compiled using gcc.         The file is read and scanned in chunks of chunksize bytes.     """    f = open(executable,'rb')    binary = f.read(chunksize)    pos = 0    while 1:        m = _libc_search.search(binary,pos)        if not m:            binary = f.read(chunksize)            if not binary:                break            pos = 0            continue        libcinit,glibc,glibcversion,so,threads,soversion = m.groups()        if libcinit and not lib:            lib = 'libc'        elif glibc:            if lib != 'glibc':                lib = 'glibc'                version = glibcversion            elif glibcversion > version:                version = glibcversion        elif so:            if lib != 'glibc':                lib = 'libc'                if soversion > version:                    version = soversion                if threads and version[-len(threads):] != threads:                    version = version + threads        pos = m.end()    f.close()    return lib,version def _dist_try_harder(distname,version,id):     """ Tries some special tricks to get the distribution        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        info = open('/var/adm/inst-log/info').readlines()        distname = 'SuSE'        for line in info:            tv = string.split(line)            if len(tv) == 2:                tag,value = tv            else:                continue            if tag == 'MIN_DIST_VERSION':                version = string.strip(value)            elif tag == 'DIST_IDENT':                values = string.split(value,'-')                id = values[2]        return distname,version,id     if os.path.exists('/etc/.installed'):        # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)        info = open('/etc/.installed').readlines()        for line in info:            pkg = string.split(line,'-')            if len(pkg) >= 2 and pkg[0] == 'OpenLinux':                # XXX does Caldera support non Intel platforms ? If yes,                #     where can we find the needed id ?                return 'OpenLinux',pkg[1],id     if os.path.isdir('/usr/lib/setup'):        # Check for slackware verson tag file (thanks to Greg Andruk)        verfiles = os.listdir('/usr/lib/setup')        for n in range(len(verfiles)-1, -1, -1):            if verfiles[n][:14] != 'slack-version-':                del verfiles[n]        if verfiles:            verfiles.sort()            distname = 'slackware'            version = verfiles[-1][14:]            return distname,version,id     return distname,version,id _release_filename = re.compile(r'(\w+)[-_](release|version)')_release_version = re.compile(r'([\d.]+)[^(]*(?:\((.+)\))?') # Note:In supported_dists below we need 'fedora' before 'redhat' as in# Fedora redhat-release is a link to fedora-release. def dist(distname='',version='',id='',          supported_dists=('SuSE', 'debian', 'fedora', 'redhat', 'mandrake')):     """ Tries to determine the name of the Linux OS distribution name.         The function first looks for a distribution release file in        /etc and then reverts to _dist_try_harder() in case no        suitable files are found.         Returns a tuple (distname,version,id) which default to the        args given as parameters.     """    try:        etc = os.listdir('/etc')    except os.error:        # Probably not a Unix system        return distname,version,id    for file in etc:        m = _release_filename.match(file)        if m:            _distname,dummy = m.groups()            if _distname in supported_dists:                distname = _distname                break    else:        return _dist_try_harder(distname,version,id)    f = open('/etc/'+file,'r')    firstline = f.readline()    f.close()    m = _release_version.search(firstline)    if m:        _version,_id = m.groups()        if _version:            version = _version        if _id:            id = _id    else:        # Unkown format... take the first two words        l = string.split(string.strip(firstline))        if l:            version = l[0]            if len(l) > 1:                id = l[1]    return distname,version,id class _popen:     """ Fairly portable (alternative) popen implementation.         This is mostly needed in case os.popen() is not available, or        doesn't work as advertised, e.g. in Win9X GUI programs like        PythonWin or IDLE.         Writing to the pipe is currently not supported.     """    tmpfile = ''    pipe = None    bufsize = None    mode = 'r'     def __init__(self,cmd,mode='r',bufsize=None):         if mode != 'r':            raise ValueError,'popen()-emulation only supports read mode'        import tempfile        self.tmpfile = tmpfile = tempfile.mktemp()        os.system(cmd + ' > %s' % tmpfile)        self.pipe = open(tmpfile,'rb')        self.bufsize = bufsize        self.mode = mode     def read(self):         return self.pipe.read()     def readlines(self):         if self.bufsize is not None:            return self.pipe.readlines()     def close(self,               remove=os.unlink,error=os.error):         if self.pipe:            rc = self.pipe.close()        else:            rc = 255        if self.tmpfile:            try:                remove(self.tmpfile)            except error:                pass        return rc     # Alias    __del__ = close def popen(cmd, mode='r', bufsize=None):     """ Portable popen() interface.    """    # Find a working popen implementation preferring win32pipe.popen    # over os.popen over _popen    popen = None    if os.environ.get('OS','') == 'Windows_NT':        # On NT win32pipe should work; on Win9x it hangs due to bugs        # in the MS C lib (see MS KnowledgeBase article Q150956)        try:            import win32pipe        except ImportError:            pass        else:            popen = win32pipe.popen    if popen is None:        if hasattr(os,'popen'):            popen = os.popen            # Check whether it works... it doesn't in GUI programs            # on Windows platforms            if sys.platform == 'win32': # XXX Others too ?                try:                    popen('')                except os.error:                    popen = _popen        else:            popen = _popen    if bufsize is None:        return popen(cmd,mode)    else:        return popen(cmd,mode,bufsize) def _norm_version(version,build=''):     """ Normalize the version and build strings and return a single        version string using the format major.minor.build (or patchlevel).    """    l = string.split(version,'.')    if build:        l.append(build)    try:        ints = map(int,l)    except ValueError:        strings = l    else:        strings = map(str,ints)    version = string.join(strings[:3],'.')    return version _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '                         '.*'                         'Version ([\d.]+))') def _syscmd_ver(system='',release='',version='',                supported_platforms=('win32','win16','dos','os2')):     """ Tries to figure out the OS version used and returns        a tuple (system,release,version).         It uses the "ver" shell command for this which is known        to exists on Windows, DOS and OS/2. XXX Others too ?         In case this fails, the given parameters are used as        defaults.     """    if sys.platform not in supported_platforms:        return system,release,version     # Try some common cmd strings    for cmd in ('ver','command /c ver','cmd /c ver'):        try:            pipe = popen(cmd)            info = pipe.read()            if pipe.close():                raise os.error,'command failed'            # XXX How can I supress shell errors from being written            #     to stderr ?        except os.error,why:            #print 'Command %s failed: %s' % (cmd,why)            continue        except IOError,why:            #print 'Command %s failed: %s' % (cmd,why)            continue        else:            break    else:        return system,release,version     # Parse the output    info = string.strip(info)    m = _ver_output.match(info)    if m:        system,release,version = m.groups()        # 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)    return system,release,version def _win32_getvalue(key,name,default=''):     """ Read a value for name from the registry key.         In case this fails, default is returned.     """    from win32api import RegQueryValueEx    try:        return RegQueryValueEx(key,name)    except:        return default def win32_ver(release='',version='',csd='',ptype=''):     """ Get additional version information from the Windows Registry        and return a tuple (version,csd,ptype) referring to version        number, CSD level and OS type (multi/single        processor).         As a hint: ptype returns 'Uniprocessor Free' on single        processor NT machines and 'Multiprocessor Free' on multi        processor machines. The 'Free' refers to the OS version being        free of debugging code. It could also state 'Checked' which        means the OS version uses debugging code, i.e. code that        checks arguments, ranges, etc. (Thomas Heller).         Note: this function only works if Mark Hammond's win32        package is installed and obviously only runs on Win32        compatible platforms.     """    # XXX Is there any way to find out the processor type on WinXX ?    # XXX Is win32 available on Windows CE ?    #    # Adapted from code posted by Karl Putland to comp.lang.python.    #    # The mappings between reg. values and release names can be found    # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp     # Import the needed APIs    try:        import win32api    except ImportError:        return release,version,csd,ptype    from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx    from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\                         VER_PLATFORM_WIN32_WINDOWS     # Find out the registry key and some general version infos    maj,min,buildno,plat,csd = GetVersionEx()    version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)    if csd[:13] == 'Service Pack ':        csd = 'SP' + csd[13:]    if plat == VER_PLATFORM_WIN32_WINDOWS:        regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'        # Try to guess the release name        if maj == 4:            if min == 0:                release = '95'            elif min == 10:                release = '98'            elif min == 90:                release = 'Me'            else:                release = 'postMe'        elif maj == 5:            release = '2000'

Lines 1–500 of 1254.