How to get user home directory on Windows

Tim Golden mail at timgolden.me.uk
Sun Jan 13 10:28:39 EST 2008


thebjorn wrote:
> On Jan 12, 6:50 pm, "Giampaolo Rodola'" <gne... at gmail.com> wrote:
>> Update.
>> I found a way for getting the home directory of the user but it
>> requires to validate the user by providing username+password:
>>
>> def get_homedir(username, password):
>>     token = win32security.LogonUser(
>>         username,
>>         None,
>>         password,
>>         win32security.LOGON32_LOGON_NETWORK,
>>         win32security.LOGON32_PROVIDER_DEFAULT
>>         )
>>     return win32profile.GetUserProfileDirectory(token)
>>
>> What I'd like to do is avoiding the requirement of the password, the
>> same way as if I would on UNIX where it would be enough just using the
>> pwd module:
>>
>>  >>> import pwd
>>  >>> pwd.getpwnam('user').pw_dir
>>  '/home/user'
> 
> Check out http://msdn2.microsoft.com/en-us/library/bb762181(VS.85).aspx
> for some of the complexities of special directories on Windows.

Part of the problem here is that is the OP is asking for the
"home dir" of a user, but there is no such thing under Windows.
Or, rather, there are several such things. The code he posts
above will get the path to what will be the user's %USERPROFILE%
env var when he logs on. (Which is certainly one of the
definitions of "home dir"). But he wants that path *without* having
to log them in. The page you refer to (and other similar suggestions
of using the os.expanduser function which essentially does the same
thing for you) assume you're already logged in as the user in question.

I've posted a (WMI-based) solution [1] on the python-win32 list
where the OP copied his question. You could do the same just with
win32security and _winreg. (Left as an exercise... etc.) Haven't
yet heard back from the OP as to whether that's given him what he
wants or not.

TJG

[1] http://mail.python.org/pipermail/python-win32/2008-January/006656.html




More information about the Python-list mailing list