Getting a hidden password from user Input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 25, 2022

banner

Photo from Unsplash

Getting a hidden password from user Input in Python #

Use the getpass() method to take a hidden password from user input, e.g. password = getpass.getpass('Enter your password: '). The getpass method prompts the user for a password and hides the text while the user is typing.

main.py
import getpass username = input('Enter your username: ') print(username) password = getpass.getpass('Enter your password: ') print(password)

user input hidden password

We used the getpass() method from the getpass module to prompt the user for input without echoing the password.

The getpass module is available in the standard library, so you don't have to install anything.

The getpass method is usually used to prompt the user for a password or other sensitive information.

The argument the method takes is the message that is displayed to the user.

If no message is provided, it defaults to "Password: ".

main.py
import getpass username = input('Enter your username: ') print(username) # 👇️ using default message password = getpass.getpass() print(password)

input password hidden default message

We didn't pass a message to the getpass() method so it displayed the default "Password: " message.

You can use the getpass() method to take any other sensitive information from the user without displaying the text, it doesn't have to be a password.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.