根据操作系统的不同,如何从用户输入中获取单个字符以及如何检查回车符将有所不同。
看到这篇文章:Python从用户那里读取一个字符
例如,在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