Berry Tsakala
Berry Tsakala

Reputation: 16610

python's os.path.expanduser('~') inconsistent windows behaviour

from os.path import expanduser
print expanduser('~')

in a "dos" box command line:

c:c:\users\myuser     <-- incorrect

in a pythonwin session:

c:\users\myuser       <-- correct

it's the same python 2.7.8 interpreter for both of the interpreters. it probably depends if i run in from the console.

if I ran a script from the command line, it will be wrong. same script running from pythonwin shows the correct version.

what's going on? (i'm on windows7)

C:\> echo %HOMEDRIVE%
C:

C:\> echo %HOMEPATH%
\Users\myuser

C:\> echo %HOME%
C:C:\Users\myuser          <--  aha!

Upvotes: 1

Views: 1543

Answers (1)

Jonah Graham
Jonah Graham

Reputation: 7970

What is happening here is Python is expanding ~ to one of the following, with this precedence:

  • %HOME%
  • %USERPROFILE%
  • %HOMEDRIVE%%HOMEPATH%

So, on your machine, I suspect HOMEPATH is defined c:\users\myuser instead of the correct \users\myuser. HOMEDRIVE is probably correctly set to c:

In your pythonwin it is probably defining HOME or USERPROFILE properly.

From the Python docs:

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

Upvotes: 4

Related Questions