【问题标题】:Inputing a hidden string on Python 3在 Python 3 上输入隐藏字符串
【发布时间】:2016-05-07 19:59:22
【问题描述】:

我目前正在 Python 3 上制作一个程序,我需要用户输入程序稍后将使用的密码。我现在遇到的问题是,如果我只使用password = input("Enter password: "),用户输入的字符将在屏幕上可见——我宁愿将它们替换为星号。

当然,我可以使用 pygame 并执行以下操作:

import pygame, sys
pygame.init()
def text (string, screen, color, position, size, flag=''):
    font = pygame.font.Font(None, size)
    text = font.render(string, 1, (color[0], color[1], color[2]))
    textpos = text.get_rect(centerx=position[0], centery=position[1])
    screen.blit(text, textpos)
    pygame.display.flip()
screen = pygame.display.set_mode((640, 480))
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
text('Enter password:', screen, [255, 0, 0], [320, 100], 36)
pygame.display.flip()
password = ''
password_trigger = True
while password_trigger:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if chr(int(str(event.key))) in alphabet:
                password += chr(int(str(event.key)))
                screen.fill((0, 0, 0))
                text('*'*len(password), screen, [0, 50, 250], [320, 360], 36)
                text('Enter password:', screen, [255, 0, 0], [320, 100], 36)
                pygame.display.flip()
            elif (event.key == pygame.K_RETURN) and (len(password) > 0):
                password_trigger = False

但这似乎有点矫枉过正(另外,pygame 显示将在一个新窗口中打开,这是我宁愿避免的)。有没有一种简单的方法可以做到这一点?

【问题讨论】:

  • 因为我在家工作,房间里没有陌生人,我真的很讨厌密码屏蔽。它给我带来无尽的悲伤。我不是唯一一个有这种感觉的人。即使在工作场所,这也不是真正的安全问题,在一定程度上是一种安全剧场形式。我建议您将其设为可选。

标签: python python-3.x input passwords user-input


【解决方案1】:

您可以使用标准的getpass 模块完全隐藏用户的输入:

>>> import getpass
>>> pw = getpass.getpass("Enter password: ")
Enter password:
>>> pw
'myPassword'

【讨论】:

  • 好的,但是我可以用星号代替密码而不是完全隐藏它吗?
  • 文档说“提示用户输入密码而不回显”,所以它看起来不是这样,但是 Python 中包含库源,所以你应该能够使用它来查看如何创建一个显示星号的修改版本。 (见svn.python.org/projects/python/trunk/Lib/getpass.py
猜你喜欢
  • 1970-01-01
  • 2022-08-03
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 2011-12-06
相关资源
最近更新 更多