Steven Vascellaro <stevois...@gmail.com> added the comment:
@matanya.stroh: Don't forget to erase the asterisks if the user hits backspace. ``` def win_getpass(prompt='Password: ', stream=None, show_asterisks=False): """Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) 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': if len(pw) > 0: pw = pw[:-1] msvcrt.putwch('\b') msvcrt.putwch(' ') msvcrt.putwch('\b') else: pw = pw + c if show_asterisks: msvcrt.putwch('*') msvcrt.putwch('\r') msvcrt.putwch('\n') return pw ``` Alternatively, could let the user define the masking character, similar to Tkinter's Entry widget. ``` def win_getpass(prompt='Password: ', stream=None, mask=''): """Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) if len(mask) > 1: raise TypeError('mask argument must be a zero- or one-character str') 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': if len(pw) > 0: pw = pw[:-1] msvcrt.putwch('\b') msvcrt.putwch(' ') msvcrt.putwch('\b') else: pw = pw + c if mask: msvcrt.putwch(mask) msvcrt.putwch('\r') msvcrt.putwch('\n') return pw ``` I'm in favor of supporting masking. While it does reveal the password length, it's an accessibility feature many users have come to expect. I'd rather have this in the standard library than have developers implement their own custom, potentially insecure methods for password input. ---------- nosy: +stevoisiak _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue32884> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com