Get User Name And Password At Runtime Using Python (2024)

It is quite common that you need to grab a logged-in user name and ask for the password from a user on an application launch.

The biggest question that comes here is — Can we grab password from user in plain text? Can password input be in plain text which can be seen while entering?

Of course not. As a password is considered one of the most sensitive data, it can not be exposed so lightly. Due to its sensitivity, either user input has to be masked or it had taken in invisible form.

Let’s learn about it in more detail.

Like every other Python application, here also we need to import the required module/package and that isgetpass.

Required Package

getpassallows us to prompt for password without having the password displayed on screen or on user’s terminal. Below is the command to installgetpass:

pip install getpass

Read User Name

getpasshas a function namedgetuser(), which gives us the login name of a currently logged-in user.

userName = getpass.getuser()

If you want to prompt a user for a user name, instead of logged-in, then you can go with the traditional way of getting input as shown below:

userName= input(‘Enter user name: ‘)

Read Password

Similar togetuser(), we havegetpass()function, which helps us with grabbing password from user without showing what is keyed-in. Here is one line to grab the password:

password = getpass.getpass()

Don’t forget to importgetpassmodule, before making a call to any of these functions.

If you would like to have a complete code walk-through, do check out my YouTube video here.

Get User Name And Password At Runtime Using Python (2024)
Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 5926

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.