Reputation: 27
Is there any builtin function that can be used for getting a password in python. I need answer like this
Input: Enter a username: abcdefg Enter a password : ******** If i enter a password abcdefgt. It shows like ********.
Upvotes: 2
Views: 1072
Reputation: 23216
There is a function in the standard library module getpass
:
>>> import getpass
>>> getpass.getpass("Enter a password: ")
Enter a password:
'hello'
This function does not echo any characters as you type.
If you absolutely must have *
echoed while the password is typed, and you are on Windows, then you can do so by butchering the existing getpass.win_getpass
to add it. Here is an example (untested):
def starred_win_getpass(prompt='Password: ', stream=None):
import sys, getpass
if sys.stdin is not sys.__stdin__:
return getpass.fallback_getpass(prompt, stream)
# print the prompt
import msvcrt
for c in prompt:
msvcrt.putwch(c)
# read the input
pw = ""
while 1:
c = msvcrt.getwch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
# PATCH: echo the backspace
msvcrt.putwch(c)
else:
pw = pw + c
# PATCH: echo a '*'
msvcrt.putwch('*')
msvcrt.putwch('\r')
msvcrt.putwch('\n')
return pw
Similarly, on unix, a solution would be to butcher the existing getpass.unix_getpass
in a similar fashion (replacing the readline
in _raw_input
with an appropriate read(1)
loop).
Upvotes: 4
Reputation: 1934
Use the getpass()
function and then print the number of stars equivalent to the number of characters in the password. This is a sample:
import getpass
pswd = getpass.getpass('Password:')
print '*' * len(pswd)
The drawback is it does not print *****
side by side.
Upvotes: 0