How do I convert a password into asterisks while it is being entered?
There is getpass()
, a function which hides the user input.
import getpass
password = getpass.getpass()
print(password)
If you're using Tkinter:
# For Python 2:
from Tkinter import Entry, Tk
# For Python 3
from tkinter import Entry, Tk
master = Tk()
Password = Entry(master, bd=5, width=20, show="*")
Password.pack()
master.mainloop()
In the shell, this is not possible. You can however write a function to store the entered text and report only a string of *'s when called. Kinda like this, which I did not write. I just Googled it.
If you want a solution that works on Windows/macOS/Linux and on Python 2 & 3, you can install the pwinput
module (formerly called stdiomask):
pip install pwinput
Unlike getpass.getpass()
(which is in the Python Standard Library), the pwinput
module can display *** mask characters as you type. It is also cross-platform, while getpass
is Linux and macOS only.
Example usage:
>>> pwinput.pwinput()
Password: *********
'swordfish'
>>> pwinput.pwinput(mask='X') # Change the mask character.
Password: XXXXXXXXX
'swordfish'
>>> pwinput.pwinput(prompt='PW: ', mask='*') # Change the prompt.
PW: *********
'swordfish'
>>> pwinput.pwinput(mask='') # Don't display anything.
Password:
'swordfish'
Unfortunately this module, like Python's built-in getpass
module, doesn't work in IDLE or Jupyter Notebook.
More details at https://pypi.org/project/pwinput/