Python有个自带的getpass模块:
- import getpass
- password = getpass.getpass('Enter password: ')
- print password
该模块继承了UNIX下的一贯风格,输入密码不回显屏蔽符。
如果需要显示屏蔽符以提示自己确实正在输入密码的话,可以使用下面的模块:
- 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
- def getpass(maskchar = "*"):
- password = ""
- while True:
- ch = getch()
- if ch == "/r" or ch == "/n":
- return password
- elif ch == "/b" or ord(ch) == 127:
- if len(password) > 0:
- sys.stdout.write("/b /b")
- password = password[:-1]
- else:
- if maskchar != None:
- sys.stdout.write(maskchar)
- password += ch
- if __name__ == "__main__":
- print "Enter password:",
- password = getpass("*")
- print password
当getpass的参数为None时不回显屏蔽符号,否则显示指定的屏蔽符号。