The Python Oracle

Getting a hidden password input

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities

--

Chapters
00:00 Question
00:38 Accepted answer (Score 504)
01:07 Answer 2 (Score 197)
01:21 Answer 3 (Score 20)
01:38 Answer 4 (Score 3)
02:16 Thank you

--

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

Accepted answer links:
[getpass.getpass()]: http://docs.python.org/library/getpass.h...
[“GetPassWarning: Can not control echo on the terminal” when running from IDLE]: https://stackoverflow.com/questions/3887...

Answer 2 links:
[getpass]: https://docs.python.org/3/library/getpas...

Answer 4 links:
[getch]: https://pypi.org/project/getch/

--

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.