cross platform application configuration files

Fernando Perez fperez528 at yahoo.com
Fri Feb 28 20:15:49 CET 2003


> My question, though, is more about where to put the file,
> and how to find it again on any platform.

You may find the code below useful.  That's what I use to find what '~'
would be in a reasonably portable manner so my code doesn't barf completely
under windows if it has to run there.

Cheers,

f.



#----------------------------------------------------------------------------
class HomeDirError(Error):
    pass

def get_home_dir():
    """Return the closest possible equivalent to a 'home' directory.

    For Posix systems, this is $HOME, and on NT it's $HOMEDRIVE\$HOMEPATH.

    Currently only Posix and NT are implemented, a HomeDirError exception is
    raised for all other OSes. """ #'
    
    if os.name == 'posix':
        return os.environ['HOME']
    elif os.name == 'nt':
        # For some strange reason, win9x returns 'nt' for os.name.
        try:
            return 
os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH'])
        except:
            try:
                # Use the registry to get the 'My Documents' folder.
                import _winreg as wreg
                key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
                                  
"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
                homedir = wreg.QueryValueEx(key,'Personal')[0]
                key.Close()
                return homedir
            except:
                return 'C:\\'
    elif os.name == 'dos':
        # Desperate, may do absurd things in classic MacOS. May work under
DOS.
        return 'C:\\'
    else:
        raise HomeDirError,'support for your operating system not
implemented.'






More information about the Python-list mailing list