我试图用星号掩盖用户输入IDLE的内容,这样他们周围的人就无法看到他们输入/输入的内容。我正在使用基本的原始输入来收集他们输入的内容。
key = raw_input('Password :: ')
用户输入密码后理想的IDLE提示:
Password :: **********
根据操作系统,如何从用户输入获取单个字符以及如何检查回车符将有所不同。
看到这篇文章:Python read a single character from the user
例如,在OSX上,您可以这样:
import sys, tty, termios
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
key = ""
sys.stdout.write('Password :: ')
while True:
ch = getch()
if ch == '\r':
break
key += ch
sys.stdout.write('*')
print
print key
如果您想要一个适用于Windows / macOS / Linux和Python 2&3的解决方案,您可以安装stdiomask
模块:
pip install stdiomask
与getpass.getpass()
(在Python标准库中)不同,stdiomask
模块可以在您键入时显示***掩码字符。
用法示例:
>>> stdiomask.getpass()
Password: *********
'swordfish'
>>> stdiomask.getpass(mask='X') # Change the mask character.
Password: XXXXXXXXX
'swordfish'
>>> stdiomask.getpass(prompt='PW: ', mask='*') # Change the prompt.
PW: *********
'swordfish'
>>> stdiomask.getpass(mask='') # Don't display anything.
Password:
'swordfish'
为了解决这个问题,我写了这个小模块pyssword来在提示符下屏蔽用户输入密码。它适用于Windows。代码如下:
from msvcrt import getch
import getpass, sys
def pyssword(prompt='Password: '):
'''
Prompt for a password and masks the input.
Returns:
the value entered by the user.
'''
if sys.stdin is not sys.__stdin__:
pwd = getpass.getpass(prompt)
return pwd
else:
pwd = ""
sys.stdout.write(prompt)
sys.stdout.flush()
while True:
key = ord(getch())
if key == 13: #Return Key
sys.stdout.write('\n')
return pwd
break
if key == 8: #Backspace key
if len(pwd) > 0:
# Erases previous character.
sys.stdout.write('\b' + ' ' + '\b')
sys.stdout.flush()
pwd = pwd[:-1]
else:
# Masks user input.
char = chr(key)
sys.stdout.write('*')
sys.stdout.flush()
pwd = pwd + char