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

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

    You best bet would be to combine os.getuid() with pwd.getpwuid():

    import os
    import pwd
    
    def get_username():
        return pwd.getpwuid( os.getuid() )[ 0 ]
    

    Refer to the pwd docs for more details:

    http://docs.python.org/library/pwd.html

提交回复
热议问题