What is the Windows equivalent of pwd.getpwnam(username).pw_dir?

前端 未结 4 1586
醉酒成梦
醉酒成梦 2021-01-05 06:05

The Python pwd module provides access to getpwnam(3) POSIX API, which can be used to get the home directory for a particular user by username, as well determini

4条回答
  •  长发绾君心
    2021-01-05 06:41

    you could go the win32api.GetUserName() (current user only) or win32net.NetUserGetInfo() (any user on any server, localhost included) route. the latter could be a bit slow since it can take some time to get this information back from the OS.

      import win32net
    
      def userDir(username):
            return win32net.NetUserGetInfo(None, username, 1).get("home_dir")
    

    alternatively you could expand the environment variable USERPROFILE on windows or HOME on unix to get the information about the currently logged in user:

      def userDir():
          if os.platform.system() == 'Windows':
              return os.environ['USERPROFILE']
          elif os.platform.system() == 'Linux':
              return os.environ['HOME'] 
          else:
              return None
    

提交回复
热议问题