How do I convert a password into asterisks while it is being entered?
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/
Masking user input in python with asterisks
Depending on the OS, how you get a single character from user input and how to check for the carriage return will be different.
See this post: Python read a single character from the user
On OSX, for example, you could so something like this:
import sys, tty, termios
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
key = ""
sys.stdout.write('Password :: ')
while True:
ch = getch()
if ch == '\r':
break
key += ch
sys.stdout.write('*')
print
print key
Related Topics
Validation of a Password - Python
How to Print a Percentage Value in Python
[] and {} VS List() and Dict(), Which Is Better
Pandas: Convert Dtype 'Object' to Int
I'm Getting "Typeerror: 'List' Object Is Not Callable". How to Fix This Error
When Do You Use 'Self' in Python
Django.Db.Utils.Operationalerror Could Not Connect to Server
Correct Style for Python Functions That Mutate the Argument
How Do Chained Comparisons in Python Actually Work
How to Get All of the Output from My .Exe Using Subprocess and Popen
Download and Save PDF File with Python Requests Module
Creating Lowpass Filter in Scipy - Understanding Methods and Units
Convert Python Strings into Floats Explicitly Using the Comma or the Point as Separators
Minimum Euclidean Distance Between Points in Two Different Numpy Arrays, Not Within
How to Left Align a Fixed Width String