1 min read

Python Getpass Module

The getpass module provides a portable way to handle password inputs securely, such as prompting for a password without echoing it to the console.

Importing the Module

import getpass

Prompting for a Password

The getpass.getpass() function prompts the user for a password without echoing. The user is prompted using the string prompt, which defaults to 'Password: '.

import getpass

try:
    p = getpass.getpass()
    print('You entered:', p)
except Exception as error:
    print('ERROR', error)

Custom Prompt

You can customize the prompt message.

p = getpass.getpass(prompt='Enter your secret code: ')

Getting the User Name

The getpass.getuser() function returns the login name of the user.

import getpass

user = getpass.getuser()
print("User:", user)

programming/python/python