Skip to content
Advertisement

Masking user input in python with asterisks [duplicate]

I am trying to mask what the user types into IDLE with asterisks so people around them can’t see what they’re typing/have typed in. I’m using basic raw input to collect what they type.

key = raw_input('Password :: ')

Ideal IDLE prompt after user types password:

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

Advertisement

Answer

Depending on the OS, how you get a single character from user input and how to check for the carriage return will be different.

See this post: Python read a single character from the user

On OSX, for example, you could so something like this:

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement