The examples in this article describe how Python implements the console input password. Share to everyone for your reference. Specific as follows:
1. Raw_input ():
PWD = raw_input (' Password: ') print pwd# password:aaa# AAA
Note: The simplest method, but not secure
2. Getpass.getpass ():
Import getpasspwd = Getpass.getpass (' Password: ') print pwd# password:# AAAA
Note: Very safe, but do not see the number of input digits, it will make people feel a bit unaccustomed, do not know that the input is not in the.
3. Msvcrt.getch ():
The code is as follows:
Import MSVCRT, Sysdef pwd_input (): chars = [] While True: Newchar = Msvcrt.getch () if Newchar in ' \ r \ n ': c4/># if it is a newline, enter end print ' break elif Newchar = = ' \b ': # If it is backspace, delete the end of an if chars: del chars[-1 ] sys.stdout.write (' \b ') # removes an asterisk, but does not know why it cannot be executed ... else: chars.append (Newchar) sys.stdout.write (' * ') # displayed as asterisk print '. Join (chars) pwd = Pwd_input ( ) Print pwd# ******# aaaaaa
Note: The second method does not show the number of input digits, but if you press BACKSPACE (BACKSPACE), the actual is backspace,
But the console does not show the corresponding backspace, for example, the current input is: ABCD, shown as: * * * *, and now hit a backspace key, the actual
The input is: ABC, and the display is still: * * *. Do not know why sys.stdout.write (' \b ') This line is not executed, is estimated to be related to the use of Msvcrt.getch (). Interested friends can further study.
Hopefully this article will help you with Python programming.