How to use getuser() function for displaying username In Python

Syntax: getpass.getuser()

The getuser() function displays the login name of the user. This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first non-empty string. 

Python




# Python program to demonstrate working of
# getpass.getuser()
import getpass
 
user = getpass.getuser()
 
while True:
    pwd = getpass.getpass("User Name : %s" % user)
 
    if pwd == 'abcd':
        print "Welcome!!!"
        break
    else:
        print "The password you entered is incorrect."


Output : 

$ python3 getpass_example3.py

User Name : bot
Welcome!!!

$ python3 getpass_example3.py

User Name : bot
The password you entered is incorrect.


getpass() and getuser() in Python (Password without echo)

getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal.

Similar Reads

getpass module provides two functions :

Using getpass() function to prompt user password...

Using getuser() function for displaying username

...