The example in this article describes how Python implements the console input password. Share to everyone for your reference. Specifically as follows:
1. Raw_input ():
?
1 2 3 4 |
PWD = raw_input (' Password: ') print pwd # password:aaa # AAA |
Note: The easiest way, but not safe
2. Getpass.getpass ():
?
1 2 3 4 5 |
Import getpass pwd = Getpass.getpass (' Password: ') print pwd # password: # AAAA |
Note: Very safe, but can not see the input of the number of digits, it will make people feel a bit unaccustomed, do not know that is not in the input.
3. Msvcrt.getch ():
The code is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23-24 |
Import MSVCRT, sys def pwd_input (): chars = [] While True:newchar = Msvcrt.getch () if Newchar in ' RN ': # If the line is wrapped, enter end Prin T ' break elif Newchar = = ' B ': # If it is a backspace, delete the end of an if Chars:del chars[-1] sys.stdout.write (' B ') # delete an asterisk, but do not know why it cannot be performed ... Els E:chars.append (Newchar) sys.stdout.write (' * ') # is displayed as an asterisk print '. Join (chars) pwd = Pwd_input () print pwd # aaaaaa |
Note: Solve the second method can not display the number of input digits, but if the backspace bar (BACKSPACE), although the actual backspace,
But the console does not display the corresponding backspace, for example, the current input is: ABCD, shown as: * * *, and now play a backspace key, the actual
Enter as: ABC, and the display is still: * * *. It is not known why Sys.stdout.write (' B ') has not been executed, and is estimated to be related to the use of Msvcrt.getch (). Interested friends can further study.
I hope this article will help you with your Python programming.