Vladimir Shevyakov
Vladimir Shevyakov

Reputation: 2831

Inputing a hidden string on Python 3

I'm currently making a program on Python 3 in which I need the user to enter a password that the program will later use. The problem I have right now is that if I simply use password = input("Enter password: ") the charcters entered by the user will be visible on-screen - and I would rather have them replaced by asterixes.

Of course, I could use pygame and do something like:

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

but that seems a little overkill (also, the pygame display will open in a new window which I something I'd rather avoid). Is there a simple way of doing this?

Upvotes: 0

Views: 899

Answers (1)

bgporter
bgporter

Reputation: 36504

You can have the user's input completely hidden using the standard getpass module:

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

Upvotes: 8

Related Questions