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 ********.
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).
getpassmodule prompts for a password with echo off, but doesn't show*****.