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

前端 未结 12 927
别那么骄傲
别那么骄傲 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:58

    Combined pwd and getpass approach, based on other answers:

    try:
      import pwd
    except ImportError:
      import getpass
      pwd = None
    
    def current_user():
      if pwd:
        return pwd.getpwuid(os.geteuid()).pw_name
      else:
        return getpass.getuser()
    

提交回复
热议问题