Python 实现“按任意键返回”和无回显输入

功能描述:

在某些应用场景中,需要实现“按任意键返回”这样的功能,在 Python 中如果使用内置函数 input() 的话必须有个回车键才表示输入结束,不够完美。

在 msvrct 标准库中,可以使用 getch()/getwch() 或 getche()/getwche() 函数实现“按任意键返回”这样的功能,其中 getch()和 getwch() 不回显,getche()和 getwche() 回显输入的字符。getwch()和 getwche() 返回 Unicode 字符,getch()和 getche() 返回字节。

另外,在标准库 getpass 中提供了 getpass 函数可以直接实现无回显输入,用来接收密码时不至于被人偷看到。1. 按任意键返回参考代码:

<code>import msvcrt

print("按任意键返回。")
msvcrt.getwche()
/<code>

2、无回显输入多字符

参考代码:

<code>import msvcrt

pwd = []
print("请输入密码:",end = "",flush = True)
while True:
ch = msvcrt.getwch()
if ch == "\\r":
break
pwd.append(ch)
print(f"\\n你输入的密码是:{"",join(pwd)}")


/<code>

3、无回显输入多字符

参考代码:

<code>import getpass

pwd = getpass.getpass("请输入密码:")
print(f"你输入的密码是:{pwd}")/<code>

<code>import getpass

pwd = getpass.getpass("请输入密码:")
print(f"你输入的密码是:{pwd}")/<code>