【问题标题】:How to get input of password, but replacing characters with '*'如何输入密码,但用“*”替换字符
【发布时间】:2017-10-02 06:07:31
【问题描述】:

标题中的所有内容真的...

我知道你可以使用

getpass.getpass()

但是,如果分发这样的代码,人们习惯于使用 '*' 来表示他们的字符,因此当他们看到屏幕上没有弹出字符时,可能会让人认为他们的键盘无法正常工作。

我想让'example' 在输入过程中显示为'*******',这样:

Enter Password: example

将显示为

Enter Password: *******

感谢您的任何回答

【问题讨论】:

  • 您可以从 getpass 更改提示,例如getpass.getpass(prompt='输入密码(注意你没有收到任何迹象表明输入了一个字符,例如一个星号):')

标签: python python-3.x


【解决方案1】:

我为您准备了一个解决方法,您可以根据自己的需要进行修改:

  1. 安装getch:pip install getch。该模块具有按字符获取输入字符的方法。
  2. 创建一个函数,逐个字符地获取用户输入并在其位置打印*

    #import sys (if option 1. is used)
    import getch
    
    def get_password():
        p = ''
        typed = ''
    
        while True:
            typed = getch.getch()
    
            if typed == '\n':
                print(typed)
                break
    
            p += typed
    
            # Choose one of the following solutions:
    
            # 1. General way. Needs import sys
            sys.stdout.write('*')
            sys.stdout.flush()
    
            # 2. Python 3 way:
            print('*', end='', flush=True)
    
       return p
    

祝你好运:)


编辑: 对于@timgeb 关于安全性的评论:

来自getpass 文档:

在 Unix 上,如果需要,使用替换错误处理程序将提示写入类文件对象流。
流默认为控制终端 (/dev/tty) 或 sys.stderr 不可用(此参数在 Windows 上被忽略)。

所以它的行为与上面的函数非常相似,除了我的没有后备选项......

【讨论】:

  • 与使用getpass 模块相比,谁能判断它的安全性?
  • 我似乎无法在 Windows 上安装 getch 模块。我该怎么办?
  • 在windows中安装msvcrt并将其用作msvcrt.getch()
  • Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> get_password() File "C:\Users\Default\Desktop\kjhgh.py", line 15, in get_password p += typed TypeError: must be str, not bytes
  • 请参阅stackoverflow.com/questions/21689365/…,因为您使用的是 Python 3,您可以改用 print() 选项!
【解决方案2】:

这个应该做的:

import msvcrt
import sys

print('Enter your password: ')
password = ''
while True:
    pressedKey = msvcrt.getch()
    if pressedKey == '\r':    
       break
    else:
        password = password+pressedKey
        sys.stdout.write('*')

print('\n' + password)

MS VC++ - 适用于 Windows 的 Microsoft Visual C++。 getpass使用这个模块,根据docs

【讨论】:

    【解决方案3】:

    真的停止重新发明轮子。不要在你的程序中包含这样的东西,而是让它使用密码帮助程序。

    https://stackoverflow.com/a/67327327/701532

    当然,如果你编写了一个很棒的密码助手,用于在 python 中输入星号,就像我多年前在 shell 中所做的那样......去吧!

    【讨论】:

      猜你喜欢
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多