Home  >  Article  >  Backend Development  >  Python实现控制台输入密码的方法

Python实现控制台输入密码的方法

WBOY
WBOYOriginal
2016-06-10 15:11:201932browse

本文实例讲述了Python实现控制台输入密码的方法。分享给大家供大家参考。具体如下:

1. raw_input() :

pwd = raw_input('password: ')
print pwd
# password: aaa
# aaa

Note: 最简单的方法,但是不安全

2. getpass.getpass() :

import getpass
pwd = getpass.getpass('password: ')
print pwd
# password:
# aaaa

Note: 很安全,但是看不到输入的位数,会让人觉得有点不习惯,不知道的还以为没有在输入..

3. msvcrt.getch() :

代码如下:

import msvcrt, sys
def pwd_input():
  chars = []
  while True:
    newChar = msvcrt.getch()
    if newChar in '\r\n':
    # 如果是换行,则输入结束
      print ''
      break
    elif newChar == '\b':
    # 如果是退格,则删除末尾一位
      if chars:
        del chars[-1]
        sys.stdout.write('\b')
        # 删除一个星号,但是不知道为什么不能执行...
    else:
      chars.append(newChar)
      sys.stdout.write('*')
      # 显示为星号
  print ''.join(chars)
pwd = pwd_input()
print pwd
# ******
# aaaaaa

Note: 解决了第二种方法不能显示输入位数的问题,但是如果按退格键(backspace)的话,虽然实际的是退格了,

但控制台却没有显示相应的退格,比如,当前输入是:abcd,显示为:****,然后现在打一个退格键,实际

输入为:abc,而显示仍为:****。不知道为什么 sys.stdout.write('\b') 这行没有执行,估计是和使用msvcrt.getch()有关系。感兴趣的朋友可以进一步研究一下。

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn