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

前端 未结 9 1974
感情败类
感情败类 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:14

    I have combined the answers of @Tigran Aivazian and @Ahndwoo into fully working solution:

    • ! additional code for the backspace {b'\x08', b'\x7f'}: # Backspace is added
    • for the Ctrl+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)
    

提交回复
热议问题