getpass() and getuser() functions in python

Hello guys, in this tutorial, we are going to learn about getpass() and getuser() functions in Python. Both of these functions are present in the getpass module of Python. These functions help us to interact with the user in a secure way. Let’s see more on this further in this tutorial.

getpass() in Python

This function prints a prompt that is provided as a parameter in the function call and then it reads the input without echo. The default prompt for it will be “Password: “. Have a look at the example code given below for a better understanding.

import getpass as gp

pwd = gp.getpass()

if (pwd == 'Yourname'):
    print('Welcome')
else:
    print("Incorrect password")

Output:

Password:
Welcome

As you can see, we have not provided any prompt string. Therefore it prints the default prompt which is “Password: “.

Another example for the getpass() has been shown here. Here we have asked a security question as prompt. See the code.

import getpass as gp

pwd = gp.getpass('Your Nickname:')

if (pwd == 'nick'):
    print('Welcome')
else:
    print("Incorrect password")

The output of the above is:

Your Nickname:
Welcome

getuser() in Python

The getuser() function returns the login name of the user from the list of environment variables. The below code explains the function very well. Have a look.

import getpass as gp

user = gp.getuser()

pwd = gp.getpass("Username: " + user)

if (pwd == 'nick'):
    print('Welcome')
else:
    print("Incorrect password")

Output:

Username: Ranjeet Verma
Welcome

Thank you.

Also read: Quine in Python

Leave a Reply