4 回答

TA貢獻1802條經驗 獲得超5個贊
返回以字節為單位。你的情況應該檢查b'\r'打破。另外,您必須flush stdout打印星號。
import sys, msvcrt
def getPassword():
sys.stdout.write('Password: ')
sys.stdout.flush()
pw = b'' #init password as bytes
while True:
char = msvcrt.getch() #get typed character - returns as bytes
if char == b'\r': #if character is return, break
break
pw += char #else concat password with character
sys.stdout.write('*') #write asterisk
sys.stdout.flush() #flush buffer to print asterisk
return pw.decode() #return password as string
pw = getPassword()
print(f'\n{pw}')

TA貢獻1788條經驗 獲得超4個贊
你應該暫時放這樣的東西:
print(x)
在通話之后getch,您可能會立即得到一些不同的'\r'東西(例如b'\r',這是我這樣做時看到的)。因此,這就是您應該比較的對象:
if x == b'\r':
也許檢查這一點的最好方法就是簡單地啟動 Python 并查看它對特定鍵的作用。以下文字記錄顯示了我按下該ENTER鍵時發生的情況:
C:\Pax> python
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import msvcrt
>>> print(msvcrt.getch())
b'\r'

TA貢獻1797條經驗 獲得超6個贊
import getpass
import sys
import msvcrt
passwor = ''
while True:
x = msvcrt.getch()
if x == '\r':
break
sys.stdout.write('*')
passwor +=str(x)
print('\n'+passwor)
您遇到了縮進錯誤。我想這可能對你有幫助。如果不是,請原諒我,因為我是這個領域的初學者

TA貢獻1827條經驗 獲得超4個贊
在 while 之前使用 break 和刪除縮進。
import getpass
import sys
import msvcrt
passwor = ''
while True:
x = msvcrt.getch()
if x == '\r':
break
sys.stdout.write('*')
passwor +=str(x)
print('\n'+passwor)
break
希望它會有所幫助:)
添加回答
舉報