我试图创建一个程序,采取用户输入,而不是显示实际输入我想用*替换输入
我已经尝试使用此代码,但我不断收到下面的错误,我将不胜感激任何指导或帮助.
import msvcrt
import sys
def userinput(prompt='>'):
write = sys.stdout.write
for x in prompt:
msvcrt.putch(x)
entry = ""
while 1:
x = msvcrt.getch()
print(repr(x))
if x == '\r' or x == '\n':
break
if x == '\b':
entry = entry[:-1]
else:
write('*')
entry = entry + x
return entry
userEntry = userinput()
Run Code Online (Sandbox Code Playgroud)
错误:
Traceback (most recent call last):
File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 24, in <module>
userEntry = userinput()
File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 9, in userinput
msvcrt.putch(x)
TypeError: putch() argument must be a byte string of length 1, not str
Run Code Online (Sandbox Code Playgroud)
Uri*_*iel -1
根据您收到的错误,putch获取的是一个字节,而不是字符串,所以使用
for x in prompt:
msvcrt.putch(x.encode()[:1])
Run Code Online (Sandbox Code Playgroud)
([:1]通常没有必要,只是为了确保字节数组的长度为 1)
比使用流更常见的做法是使用msvcrt.getch并循环直到获得换行符,同时打印用户输入长度的字符串,*每次都充满,并在打印函数末尾通过回车符打印到同一行:
import msvcrt
def getch():
return chr(msvcrt.getch()[0])
def hidden_input (input_message = 'enter input:'):
user_input = ''
new_ch = ''
while new_ch != '\r':
print(input_message, '*' * len(user_input), ' ' * 20, end = '\r')
user_input = user_input[:-1] if new_ch == '\b' else user_input + new_ch
new_ch = getch()
return user_input
hidden_input()
Run Code Online (Sandbox Code Playgroud)