我写了一个模块来大致说明您是如何独立地使用it平台的。#!/usr/bin/python2
def _masked_input_unix(prompt="Password: ", mask="*"):
pw = ""
# save terminal settings
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
# setup 'cbreak' mode
new[3] = new[3] & ~termios.ECHO
new[3] = new[3] & ~termios.ICANON
new[6][termios.VMIN] = '\x01'
new[6][termios.VTIME] = '\x00'
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
print prompt,
# Read the password
while True:
c = sys.stdin.read(1)
# submit chars
if c == '\r' or c == '\n':
sys.stdout.write("%s" % (c))
break
# delete chars
elif c == '\b' or c == '\x7f':
if len(pw) > 0:
pw = pw[:-1]
sys.stdout.write("%s" % ('\b \b'))
# password chars
else:
pw += c
sys.stdout.write("%s" % (mask))
finally:
# ensure we reset the terminal
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return pw
def _masked_input_win(prompt="Password: ", mask='*'):
pw = ""
while True:
c = msvcrt.getch()
# submit chars
if c == '\r' or c == '\n':
while msvcrt.kbhit():
msvcrt.getch()
break
elif c == '\x03':
raise KeyboardInterrupt
# delete chars
elif c == '\b' or c == '\x7f':
if len(pw) > 0:
pw = pw[:-1]
msvcrt.putch('\b')
msvcrt.putch(' ')
msvcrt.putch('\b')
# password chars
else:
pw += c
msvcrt.putch(mask)
return pw
## initialize windows or posix function pointer
masked_input = None
try:
import msvcrt
masked_input = _masked_input_win
except ImportError:
import sys, termios
masked_input = _masked_input_unix
if __name__ == "__main__":
p = masked_input()
print "Password is:", p
这适用于单字节编码。添加unicode支持是非常重要的。我怀疑unicode不能很好地与Windows上的getpass模块一起工作。(注意:这并不像将所有内容更改为unicode字符串和使用getwch()那么简单)