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

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

    You can do this:

    # if getch module is available, then we implement our own getpass() with asterisks,
    # otherwise we just use the plain boring getpass.getpass()
    try:
        import getch
        def getpass(prompt):
            """Replacement for getpass.getpass() which prints asterisks for each character typed"""
            print(prompt, end='', flush=True)
            buf = ''
            while True:
                ch = getch.getch()
                if ch == '\n':
                    print('')
                    break
                else:
                    buf += ch
                    print('*', end='', flush=True)
            return buf
    except ImportError:
        from getpass import getpass
    

提交回复
热议问题