Hiding Raw_Input() Password Input

Getting a hidden password input

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.

Is it possible to make user input invisible as a 'sudo' password input?

You need the getpass module.

from getpass import getpass
password = getpass()

How to hide passwd and show ' * ' under Python

If all else fails, you could modify the getpass library (you can't sub-class it, unfortunately).

e.g. The code for windows (source):

def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return fallback_getpass(prompt, stream)
import msvcrt
import random
for c in prompt:
msvcrt.putwch(c)
pw = ""
while 1:
c = msvcrt.getwch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
else:
pw = pw + c
stars = random.randint(1,3)
for i in range(stars):
msvcrt.putwch('*') #<= This line added
msvcrt.putwch('\r')
msvcrt.putwch('\n')
return pw

Should print a '*' for every character entered.

Edit:

getpass() is stated to be incompatible with Python 2, and on Python 2 (At least on my machine), putwch() gives TypeError: must be cannot convert raw buffers, not str.

This can be resolved by changing:

msvcrt.putwch(c) to msvcrt.putwch(unicode(c))

and

msvcrt.putwch('str') to msvcrt.putwch(u'str')

Or simply replacing putwch() with putch() if you don't need to deal with unicode.

Edit2:

I've added a random element so that it will print 1-3 stars for each keypress

Enter hidden password in python

According to your comment above, you are actually using ipython within spyder. The only issue I came across for getpass in Spyder is at their Google code page. The issues is not exactly the same as yours, but included in the comments is the following code snippet:

def spyder_getpass(prompt='Password: '):
set_spyder_echo(False)
password = raw_input(prompt)
set_spyder_echo(True)
return password

Try using the method above (utilizing raw_input instead of getpass) to get the required password you need.



Related Topics



Leave a reply



Submit