How to Convert a Password into Asterisks While It Is Being Entered

How do I convert a password into asterisks while it is being entered?

If you want a solution that works on Windows/macOS/Linux and on Python 2 & 3, you can install the pwinput module (formerly called stdiomask):

pip install pwinput

Unlike getpass.getpass() (which is in the Python Standard Library), the pwinput module can display *** mask characters as you type. It is also cross-platform, while getpass is Linux and macOS only.

Example usage:

>>> pwinput.pwinput()
Password: *********
'swordfish'
>>> pwinput.pwinput(mask='X') # Change the mask character.
Password: XXXXXXXXX
'swordfish'
>>> pwinput.pwinput(prompt='PW: ', mask='*') # Change the prompt.
PW: *********
'swordfish'
>>> pwinput.pwinput(mask='') # Don't display anything.
Password:
'swordfish'

Unfortunately this module, like Python's built-in getpass module, doesn't work in IDLE or Jupyter Notebook.

More details at https://pypi.org/project/pwinput/

Masking user input in python with asterisks

Depending on the OS, how you get a single character from user input and how to check for the carriage return will be different.

See this post: Python read a single character from the user

On OSX, for example, you could so something like this:

import sys, tty, termios

def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

key = ""
sys.stdout.write('Password :: ')
while True:
ch = getch()
if ch == '\r':
break
key += ch
sys.stdout.write('*')
print
print key


Related Topics



Leave a reply



Submit