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

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


Look at getpass module

import getpassgetpass.getuser()'kostya'

Availability: Unix, Windows


p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."


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

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

Refer to the pwd docs for more details:

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


You can also use:

 os.getlogin()


matomo