什么是Windows等价的pwd.getpwnam(用户名).pw_dir?

Python pwd模块提供对getpwnam(3)POSIX API的访问,该API可用于通过用户名获取特定用户的主目录,以及确定用户名是否有效.如果使用不存在的用户名调用,pwd.getpwnam将引发异常.

起初,似乎可以通过os.path.expanduser(‘~username’)以跨平台方式实现相同的结果.但是,似乎在Windows XP上使用Python 2.6,这实际上不会导致不存在的用户名失败.此外,在Windows XP上的Python 2.5上,即使对于有效用户来说似乎也失败了.

可以在Windows上可靠地获取此信息吗?怎么样?

阅读 2.6 documentation表明os.path.expanduser()在Windows上被破坏:

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.

说什么?这假设所有用户家庭必须位于同一父目录下.新加坡国立大学医院,唉!

这有点难以挖掘,但这里有一个解决方案,它将通过给定名称查找本地用户

from win32security import LookupAccountName,ConvertSidToStringSid
from _winreg import OpenKey,QueryValueEx,HKEY_LOCAL_MACHINE

def getUserDir(userName):
    ssid = ConvertSidToStringSid(LookupAccountName(None,userName)[0])
    key = OpenKey(HKEY_LOCAL_MACHINE,r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\\' + ssid)
    return QueryValueEx(key,'ProfileImagePath')[0]

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...