How Python implements the console input password

Source: Internet
Author: User
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.

  • 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.