The Python Oracle

Getting a hidden password input

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Getting A Hidden Password Input
00:23 Accepted Answer Score 570
00:48 Answer 2 Score 207
00:59 Answer 3 Score 21
01:12 Answer 4 Score 4
01:38 Thank you

--

Full question
https://stackoverflow.com/questions/9202...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #passwords #userinput

#avk47



ACCEPTED ANSWER

Score 570


Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is "Password: ".

Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.




ANSWER 2

Score 207


import getpass

pswd = getpass.getpass('Password:')

getpass works on Linux, Windows, and Mac.




ANSWER 3

Score 21


This code will print an asterisk instead of every letter.

import sys
import msvcrt

passwor = ''
while True:
    x = msvcrt.getch()
    if x == '\r':
        break
    sys.stdout.write('*')
    passwor +=x

print '\n'+passwor



ANSWER 4

Score 4


Updating on the answer of @Ahmed ALaa

# import msvcrt
import getch

def getPass():
    passwor = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        passwor +=x
    return passwor

print("\nout=", getPass())

msvcrt us only for windows, but getch from PyPI should work for both (I only tested with linux). You can also comment/uncomment the two lines to make it work for windows.