诅咒 - 将 getstr 输入替换为 *星号

问题描述

我希望 getstr 在按下某个键时显示 *(星号),基本上就像一个密码登录表单。 关于如何做到这一点的任何线索? (类似于getpass

所以如果我输入 abcd 它将返回 **** (abcd)

我不知道这个问题是否已经得到解答。

解决方法

您可以通过 getch() 将用户的输入作为一系列字符

然后在每次输入后打印 *

[编辑]:

忘记处理退格键:-

请参考以下更健壮的代码:

import sys
import msvcrt

def encriptAndsavePassword():
    password = ''
    while True:
        x = ord(msvcrt.getch())
        if x == 13:
            # When system receives a carriage return character
            sys.stdout.write('\n')
            return password
        elif x == 8:
            if len(password) > 0:
                # Deletes previous character.
                sys.stdout.write('\b' + ' ' + '\b')                
                sys.stdout.flush()
                password = password[:-1] 
        else:
            sys.stdout.write('*')
            password +=x

您可以从here

阅读getch()