Is there a portable way to get the current username in Python?

前端 未结 12 1028
别那么骄傲
别那么骄傲 2020-11-22 03:11

Is there a portable way to get the current user\'s username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid

12条回答
  •  天命终不由人
    2020-11-22 03:44

    If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library.

    >>> os.path.expanduser('~')
    'C:\\Documents and Settings\\johnsmith'
    

    Also you could parse such string to get only last path component (ie. user name).

    See: os.path.expanduser

提交回复
热议问题