Python's method of implementing a console input password

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.