Skip to content

Instantly share code, notes, and snippets.

@m-bartlett
Created June 17, 2022 17:40
Show Gist options
  • Save m-bartlett/9ec0b5a92cce112f270a0330f0a79199 to your computer and use it in GitHub Desktop.
Save m-bartlett/9ec0b5a92cce112f270a0330f0a79199 to your computer and use it in GitHub Desktop.
Python one-filer password input with obscured character echoing for input visual feedback, avoids needing any external dependencies
import sys
import termios
import atexit
def password_input(prompt="Enter password: "):
fd = sys.stdin.fileno()
iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(fd)
def _restore_tty():
termios.tcsetattr(fd, termios.TCSANOW, [iflag,oflag,cflag,lflag|termios.ECHO|termios.ICANON,ispeed,ospeed,cc])
atexit.register(_restore_tty) # restore tty on unexpected exit
lflag = lflag & ~(termios.ECHO | # disable echoing user input to tty
termios.ICANON ) # disable canonical mode (make character input immediate)
termios.tcsetattr(fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] )
password, echo_str = "", ""
while True:
print(f"\r\033[2K{prompt}{echo_str}", end='', file=sys.stderr)
char = sys.stdin.read(1)
if char == '\n': # newline/return key to finalize input
break
elif char == '\x1b': # exit key to cancel
raise KeyboardInterrupt
elif char == '\x7f': # backspace to delete backwards
echo_str = echo_str[:-1]
password = password[:-1]
elif char.isascii(): # append all other ASCII characters as password string characters
echo_str += '*'
password += char
else: continue # ignore any other unexpected inputs
_restore_tty()
atexit.unregister(_restore_tty)
print("\r\033[2K", end='', file=sys.stderr)
return password
@m-bartlett
Copy link
Author

Demo

demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment