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>
Python 實現“按任意鍵返回”和無回顯輸入

<code>import getpass

pwd = getpass.getpass("請輸入密碼:")
print(f"你輸入的密碼是:{pwd}")/<code>


分享到:


相關文章: