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

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

提交回复
热议问题