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

前端 未结 9 1998
感情败类
感情败类 2020-11-28 13:31

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

9条回答
  •  情书的邮戳
    2020-11-28 14:07

    For anyone who would actually want to have asterisks appear, here's an improvement on Tigran Aivazian's answer. This version imports the built-in msvcrt.getch, adds cases for different line endings when hitting 'Enter/Return', and includes logic to support Backspace, as well as Ctrl+C (KeyboardInterrupt):

    try:
        from msvcrt 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()
                if ch in {b'\n', b'\r', b'\r\n'}:
                    print('')
                    break
                elif ch == b'\x08': # Backspace
                    buf = buf[:-1]
                    print(f'\r{(len(prompt)+len(buf)+1)*" "}\r{prompt}{"*" * len(buf)}', end='', flush=True)
                elif ch == b'\x03': # Ctrl+C
                    raise KeyboardInterrupt
                else:
                    buf += ch
                    print('*', end='', flush=True)
            return buf.decode(encoding='utf-8')
    except ImportError:
        from getpass import getpass
    

    Please feel free to suggest any other changes, or ways to improve this; I hacked the changes together pretty quickly, especially with the Backspace logic.

提交回复
热议问题