[Python] How to enter a password on the console

Source: Internet
Author: User

1. raw_input ():

PWD = Raw_input ( ' Password: ' )
Print PWD
# Password: AAA
# Aaa

Note: The simplest but Insecure Method

 

2. getpass. getpass ():

Import Getpass
PWD = Getpass. getpass ( ' Password: ' )
Print PWD
# Password:
# Aaaa

Note:It's safe, but you can't see the number of digits in the input. You may feel a little unaccustomed ..

 

3. msvcrt. getch (): 

Code Import Msvcrt, sys

Def Pwd_input ():
Chars = []
While True:
Newchar = Msvcrt. getch ()
If Newchar In   ' \ R \ n ' : # If it is a line feed, the input ends.
Print   ''
Break
Elif Newchar =   ' \ B ' : # If it is a return, the last digit is deleted.
If Chars:
Del Chars [ - 1 ]
SYS. stdout. Write ( ' \ B ' ) # Delete an asterisk, but do not know why it cannot be executed...
Else :
Chars. append (newchar)
SYS. stdout. Write ( ' * ' )#Displayed as asterisks
Print   '' . Join (chars)

PWD=Pwd_input ()
PrintPWD

#******
#Aaaaaa

Note:Solved the problem that the second method cannot display the number of input digits. However, if you press the backspace key, although the actual difference is,

However, the console does not display the corresponding backspace. For example, if the current input is "ABCD", it is displayed as "*****", and now a backspace key is entered.

The input value is ABC, but it is still :****. I don't know whySYS. stdout. Write ('\ B'This line is not executed. It is estimated that it is used and

Msvcrt. getch () is related. If someone knows why, please reply, 3q ~

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.