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

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

    You can probably use:

    os.environ.get('USERNAME')
    

    or

    os.environ.get('USER')
    

    But it's not going to be safe because environment variables can be changed.

    0 讨论(0)
  • 2020-11-22 03:41

    To me using os module looks the best for portability: Works best on both Linux and Windows.

    import os
    
    # Gives user's home directory
    userhome = os.path.expanduser('~')          
    
    print "User's home Dir: " + userhome
    
    # Gives username by splitting path based on OS
    print "username: " + os.path.split(userhome)[-1]           
    

    Output:

    Windows:

    User's home Dir: C:\Users\myuser

    username: myuser

    Linux:

    User's home Dir: /root

    username: root

    No need of installing any modules or extensions.

    0 讨论(0)
  • 2020-11-22 03:42

    Using only standard python libs:

    from os import environ,getcwd
    getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
    user = getUser()
    

    Works on Windows, Mac or Linux

    Alternatively, you could remove one line with an immediate invocation:

    from os import environ,getcwd
    user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
    
    0 讨论(0)
  • 2020-11-22 03:43

    You can also use:

     os.getlogin()
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 03:48

    I wrote the plx module some time ago to get the user name in a portable way on Unix and Windows (among other things): http://www.decalage.info/en/python/plx

    Usage:

    import plx
    
    username = plx.get_username()
    

    (it requires win32 extensions on Windows)

    0 讨论(0)
提交回复
热议问题