Masking Input on Windows
Masking password input with feedback
If an application asks a user for sensitive information from the command line, ideally one should be able to do this:
username = input("Username")
password = input("Password", masked=True) # error
However, that's not supported. Python offers the getpass
module which is like this:
import getpass
password = getpass.getpass("Password")
Password
While this effectively hides the password, I prefer to give feedback on how many characters have been entered (indicated with '*')
Created: 2020-06-20
Updated: 2021-04-29
import msvcrt
def win_getpass(prompt='Password: ', stream=None, placeholder="*"):
"""Prompt for password with echo off, using Windows getch()."""
for c in prompt:
msvcrt.putwch(c)
pw = ""
while 1:
c = msvcrt.getwch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
# User enters the backspace key
pw = pw[:-1]
# Move one character left
msvcrt.putwch('\b')
# Overwrite placeholder with whitespace
msvcrt.putwch(' ')
# Move one character left, again
msvcrt.putwch('\b')
else:
pw = pw + c
msvcrt.putwch(placeholder)
msvcrt.putwch('\r')
msvcrt.putwch('\n')
return pw