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

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

    For UNIX, at least, this works...

    import commands
    username = commands.getoutput("echo $(whoami)")
    print username
    

    edit: I just looked it up and this works on Windows and UNIX:

    import commands
    username = commands.getoutput("whoami")
    

    On UNIX it returns your username, but on Windows, it returns your user's group, slash, your username.

    --

    I.E.

    UNIX returns: "username"

    Windows returns: "domain/username"

    --

    It's interesting, but probably not ideal unless you are doing something in the terminal anyway... in which case you would probably be using os.system to begin with. For example, a while ago I needed to add my user to a group, so I did (this is in Linux, mind you)

    import os
    os.system("sudo usermod -aG \"group_name\" $(whoami)")
    print "You have been added to \"group_name\"! Please log out for this to take effect"
    

    I feel like that is easier to read and you don't have to import pwd or getpass.

    I also feel like having "domain/user" could be helpful in certain applications in Windows.

提交回复
热议问题