用星号屏蔽python中的用户输入

2024-06-02 04:27:34 发布

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

我试着用星号把用户输入的内容屏蔽成空闲状态,这样周围的人就看不到他们输入的内容。我使用基本的原始输入来收集他们输入的内容。

key = raw_input('Password :: ')

用户键入密码后理想的空闲提示:

Password :: **********

Tags: key用户密码内容inputraw键入状态
3条回答

如果您想要在Windows/macOS/Linux和Python 2&3上运行的解决方案,可以安装stdiomask模块:

pip install stdiomask

getpass.getpass()(在Python标准库中)不同,stdiomask模块可以在您键入时显示***掩码字符。

示例用法:

>>> stdiomask.getpass()
Password: *********
'swordfish'
>>> stdiomask.getpass(mask='X') # Change the mask character.
Password: XXXXXXXXX
'swordfish'
>>> stdiomask.getpass(prompt='PW: ', mask='*') # Change the prompt.
PW: *********
'swordfish'
>>> stdiomask.getpass(mask='') # Don't display anything.
Password:
'swordfish'

有关详细信息,请访问https://pypi.org/project/stdiomask/

为了解决这个问题,我编写了这个小模块pyssword,在提示时屏蔽用户输入的密码。它和窗户一起用。代码如下:

from msvcrt import getch
import getpass, sys

def pyssword(prompt='Password: '):
    '''
        Prompt for a password and masks the input.
        Returns:
            the value entered by the user.
    '''

    if sys.stdin is not sys.__stdin__:
        pwd = getpass.getpass(prompt)
        return pwd
    else:
        pwd = ""        
        sys.stdout.write(prompt)
        sys.stdout.flush()        
        while True:
            key = ord(getch())
            if key == 13: #Return Key
                sys.stdout.write('\n')
                return pwd
                break
            if key == 8: #Backspace key
                if len(pwd) > 0:
                    # Erases previous character.
                    sys.stdout.write('\b' + ' ' + '\b')                
                    sys.stdout.flush()
                    pwd = pwd[:-1]                    
            else:
                # Masks user input.
                char = chr(key)
                sys.stdout.write('*')
                sys.stdout.flush()                
                pwd = pwd + char

根据操作系统的不同,如何从用户输入中获取单个字符以及如何检查回车将有所不同。

看这篇文章:Python read a single character from the user

例如,在OSX上,您可以这样做:

import sys, tty, termios

def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

key = ""
sys.stdout.write('Password :: ')
while True:
    ch = getch()
    if ch == '\r':
        break
    key += ch
    sys.stdout.write('*')
print
print key

相关问题 更多 >