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

Look at getpass module

import getpass
getpass.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)."


Combine os.getuid() with pwd.getpwuid():

import os
import pwd

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

See pwd docs for more details.


Windows:

os.environ.get('USERNAME')

Linux:

os.environ.get('USER')

Both:

os.environ.get('USER', os.environ.get('USERNAME'))

Note that environment variables can be modified by the user, so this is a potential security vulnerability. With this method, an attacker can easily fake their username.


You can also use:

os.getlogin()