1. 按
在某些应用场景中,需要实现"按任意键返回"这样的功能,在Python中如果使用内置函数input()的话必须有个回车键才表示输入结束,不够完美。
在msvrct标准库中,可以使用getch()/getwch()或getche()/getwche()函数实现"按任意键返回"这样的功能,其中getch()和getwch()不回显,getche()和getwche()回显输入的字符。getwch()和getwche()返回Unicode字符,getch()和getche()返回字节。
另外,在标准库getpass中提供了getpass函数可以直接实现无回显输入,用来接收密码时不至于被人偷看到。
2. 按任意键返回
import msvcrt
print("Press any key to quit.")
# msvcrt.getche()
msvcrt.getch()
3. 无回显输入密码
3.1. getwch function
import msvcrt
pwd = []
print('Input your password:', end='', flush=True)
while True:
ch = msvcrt.getwch( )
if ch == '\r':
break
pwd.append(ch)
print(f'\nYour password is : {"" .join(pwd)}')
3.2. getpass function
import getpass
# 不能以调试模式运行程序
# You shoud run the code without debugging.
pwd = getpass.getpass("Input your password:")
print(f'\nYour password is : {"" .join(pwd)}')