msvcrt.getch()不知为何会先返回string输入,再返回bytes输入,导致每一次输入都会多一次循环,所以直接在最后限制了
# -*- coding: utf-8 -*-
import msvcrtdef password_input():
chars = []
while True:
char = msvcrt.getch().decode('utf8')
if char == '\r' or char =='\n':
break
elif char == '\b':
if len(chars) >= 1:
chars = chars[:-1]
msvcrt.putch(b'\b')
msvcrt.putch(b'\x20') #\x20 means space
msvcrt.putch(b'\b')
else:
continue
else:
if char != '\x00':
chars.append(char)
msvcrt.putch(b'*')
return ''.join(chars)
password = password_input()
print('The password is:',password)