Is there a way in Python to convert characters as they are being entered by the user to asterisks, like it can be seen on many websites?
For example, if an email use
I have combined the answers of @Tigran Aivazian and @Ahndwoo into fully working solution:
{b'\x08', b'\x7f'}: # Backspace
is addedCtrl+C
combination the silent return is used. The raise KeyboardInterrupt
is commented now, but can be uncommented for raise the error.# if getch module is available, then we implement our own getpass() with asterisks,
# otherwise we just use the plain boring getpass.getpass()
try:
from getch import getch
def getpass(prompt):
"""Replacement for getpass.getpass() which prints asterisks for each character typed"""
print(prompt, end='', flush=True)
buf = b''
while True:
ch = getch().encode()
if ch in {b'\n', b'\r', b'\r\n'}:
print('')
break
elif ch == b'\x03': # Ctrl+C
# raise KeyboardInterrupt
return ''
elif ch in {b'\x08', b'\x7f'}: # Backspace
buf = buf[:-1]
print(f'\r{(len(prompt)+len(buf)+1)*" "}\r{prompt}{"*" * len(buf)}', end='', flush=True)
else:
buf += ch
print('*', end='', flush=True)
return buf.decode(encoding='utf-8')
except ImportError:
from getpass import getpass
password = getpass('Enter password: ')
print(password)