expanduser on windows and wxGlade

Trent Mick trentm at ActiveState.com
Wed Dec 11 17:21:35 EST 2002


[Florian Schulze wrote]
> > > it seems like os.path.expanduser doesn't work as it should on
> > > windows, or I don't understand how it works.
> > > I get this:
> > > >>> os.path.expanduser("~")
> > > '%USERPROFILE%'


> > Depends on what your environment settings are. os.path.expanduser on
> > Windows first uses your "HOME" env var if it exists. Next it tries to
> > use HOMEPATH and HOMEDRIVE env. vars. After that it gives up. What are
> > your HOME, HOMEPATH, and HOMEDRIVE environment variables?
> > 
> > If you look in the registry under:
> >     HKCU/Environment
> > and
> >     HKLM/Environment
> > are any of HOME, HOMEPATH, or HOMEDRIVE set to "%USERPROFILE%"?


> Yes, HOME is set to %USERPROFILE%, but isn't that the default? I can't

Nope. On Win2k (or on _any_ Windows I believe) there is no HOME
environment variable by default.

> remember that I ever changed that. TMP and TEMP for example also contain
> %USERPROFILE% and USERPROFILE is set when I type set on the commandline. I
> think expanduser should also expand any environment variables as far as it
> can. I can't even use expandvars, as it expects $varname, not %varname%.

The only good work around I know for this is to use the actual value of
USERPROFILE for HOME rather than relying on %USERPROFILE% to be expanded
when you expect. I have hit this before and gave up trying to figure out
when this %FOO% expansion is being done.

You *could* also write your own expandvars() method for Windows. It
should not be too hard to write with re.sub(). Here is an attempt:

>>> import os
>>> def expandvars(s):
...     import re
...     return re.sub("%(\w+)%",
...                   lambda m: os.environ.get(m.group(1), ""),
...                   s
...                  )
...
>>> expandvars("foo's home is %HOME% %H O M E%")
"foo's home is d:\\trentm %H O M E%"
>>> expandvars("HOME is %HOME%, this one is not expanded %H O M E%")
'HOME is d:\\trentm, this one is not expanded %H O M E%'
>>> expandvars("USERPROFILE is '%USERPROFILE%'")
"USERPROFILE is 'C:\\Documents and Settings\\trentm'"


Trent

-- 
Trent Mick
TrentM at ActiveState.com




More information about the Python-list mailing list