getting user's home directory on windows

K

K.S.Sreeram

Hi everybody,

I'm having trouble using os.path.expanduser('~') on windows. It uses
$HOME or ($HOMEDRIVE+$HOMEPATH), but this doesn't work with windows
machines which are part of a domain. On such machines, the HOME envvar
may not be set at all, and the HOMEPATH envvar may be set to '\\'!!

Here's an implementation of getHomeDir which tries to find the best
possible option. I don't know how this'll behave on older versions of
windows such as win2k or win98. Please let me know if anybody knows a
better way to do this :

def getHomeDir() :
if sys.platform != 'win32' :
return os.path.expanduser( '~' )

def valid(path) :
if path and os.path.isdir(path) :
return True
return False
def env(name) :
return os.environ.get( name, '' )

homeDir = env( 'USERPROFILE' )
if not valid(homeDir) :
homeDir = env( 'HOME' )
if not valid(homeDir) :
homeDir = '%s%s' % (env('HOMEDRIVE'),env('HOMEPATH'))
if not valid(homeDir) :
homeDir = env( 'SYSTEMDRIVE' )
if homeDir and (not homeDir.endswith('\\')) :
homeDir += '\\'
if not valid(homeDir) :
homeDir = 'C:\\'
return homeDir

[sreeram;]

ps:
A bit of googling around got me this informative post:
http://www.mail-archive.com/[email protected]/msg05565.html


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFEvP5/rgn0plK5qqURAgWQAKCUfnBT4hBD14i/rG5EXzzH0Dx/ygCgjHdc
AnGSwSZ64odBbfneQXw1mEg=
=9UJP
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top