Finding user's home dir

Timothy Grant timothy.grant at gmail.com
Wed Feb 2 15:55:22 EST 2005


On Wed, 02 Feb 2005 11:30:34 -0800 (PST), Nemesis
<nemesis at nowhere.invalid> wrote:
> Hi all, I'm trying to write a multiplatform function that tries to
> return the actual user home directory. I saw that
> os.path.expanduser("~") works on Linux but on Windows2000 (at least on
> the win I used) it returns %USERPROFILE%, so I tried os.environ["HOME"]
> and it gave me the same results. So I ended up with
> os.environ["USERPROFILE"], it doesn't work on Linux but (at least) on
> Windows2000 it returns the correct information
> 
> I googled a little bit and it seems that there is no general solution,
> so I tried to merge what I found, and I wrote this little function:
> 
> def getHomeDir():
>     ''' Try to find user's home directory, otherwise return current directory.'''
>     try:
>         path1=os.path.expanduser("~")
>     except:
>         path1=""
>     try:
>         path2=os.environ["HOME"]
>     except:
>         path2=""
>     try:
>         path3=os.environ["USERPROFILE"]
>     except:
>         path3=""
> 
>     if not os.path.exists(path1):
>         if not os.path.exists(path2):
>             if not os.path.exists(path3):
>                 return os.getcwd()
>             else: return path3
>         else: return path2
>     else: return path1
> 
> Please, could you test it on your systems and tell me what you got?
> I'd like to know what it returns on different operating systems because
> I'm developing a multiplatform software.
> 
> Thank you all.
> --
> Unauthorized amphibians will be toad away.
> 
>  |\ |       |HomePage   : http://nem01.altervista.org
>  | \|emesis |XPN (my nr): http://xpn.altervista.org
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Works beautifully on my PowerBook running Mac OSX 10.3.7

/Users/timothygrant

-- 
Stand Fast,
    tjg.



More information about the Python-list mailing list