如何获取密码输入,但将字符替换为“*”

2024-10-01 17:41:46 发布

您现在位置:Python中文网/ 问答频道 /正文

标题里都是真的。。。在

我知道你可以用

getpass.getpass()

然而,如果发布这样的代码,人们习惯于用“*”表示字符,这样可能会给人一种印象,让他们在看到屏幕上没有字符弹出时,认为键盘不工作。在

我希望在输入过程中将'example'显示为'*******',以便:

^{pr2}$

会显示为

Enter Password: *******

谢谢你的回答


Tags: 代码标题屏幕examplepassword键盘字符enter
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)

微软工作的Windows Visual C++是^ {< CD1>}。getpass使用这个模块,根据{a1}

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

  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文档:

On Unix, the prompt is written to the file-like object stream using the replace error handler if needed.
stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows).

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

相关问题 更多 >

    热门问题