How to get username in Python?

Print Current User Account Name in Python

Here is the simple way to get the user name by using python code.

Note: It is adviced not to use this function for any authorization purpose as this can be manipulated. Because the getpass reads the data from environment variables (LOGNAME or USERNAME) and returns the username. Read the 2 external references mentioned at end of this page to know indepth details about this function.

Option 1: This code gets current logged in Username in Unix & Windows systems.

import getpass 
username = getpass.getuser() 
print (username)

Option 2: There is another variant of the above function. Though this will also work in Unix & Windows, it is adviced to use the getpass, because it is more stable than other functions.

import os
username = os.getlogin()
print(username)

This command directly gets the user name and returns the name as string. getpass.getuser.

External References:

  1. Discussion on getting username using Python – Read more
  2. Further reading about getpass module – Read more