Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python getpass Module

Python getpass module enables to prompt the user for a password without displaying it on the screen. Thus, it will customize the user’s experience.

It provides a secure and independent way of fetching the passwords from the command prompt.

Python getpass Module Examples

Import:

import getpass

Syntax:

getpass.getpass([prompt[, stream]])

Simple Example:

import getpass

try:
    pass_word = getpass.getpass()
except Exception as E:
    print('There is an Error : ', E)
else:
    print('Password fetched from command prompt :', pass_word)

Output:

Password: Safa
Password fetched from command prompt : Safa

1. getpass module with no prompt

Getpass Module
Getpass Module

2. getpass module with custom prompt

import getpass

place = getpass.getpass(prompt = 'Which is your favorite place to go?')
if place == 'Satara':
    print('Ofcourse!')
else:
    print('Where is that?')

Output:

Which is your favorite place to go?
Ofcourse!
Getpass Module With Custom Prompt
Getpass Module With Custom Prompt

3. getpass module with other streams

import getpass
import sys

pass_word = getpass.getpass(stream=sys.stderr)
print('Entered password:', pass_word)

Output:

Password:
Entered password: Safa
Getpass Module With Other Stream
Getpass Module With Other Stream

4. getpass(argument) function

The getpass(argument) function enables us to print the prompt string on the command-prompt.

If the argument is omitted, it prints ‘Password:’.

import getpass

user = getpass.getuser()

pass_word = getpass.getpass("User's password %s: " % user)

print(user, pass_word)

Output:

User's password HP:
HP safa

5. getuser() function

The getuser() function basically returns the corresponding login name of the user/system.

getpass.getuser()

Output:

HP

Conclusion

Thus, in this article, we have studied and implemented the getpass module in Python.


References

Leave a Reply

Your email address will not be published. Required fields are marked *