Skip to content

Instantly share code, notes, and snippets.

@mjuenema
Created February 20, 2018 01:31
Show Gist options
  • Save mjuenema/b4092799b5cfc9218d0f31c94a58cbd0 to your computer and use it in GitHub Desktop.
Save mjuenema/b4092799b5cfc9218d0f31c94a58cbd0 to your computer and use it in GitHub Desktop.
Python password input

I tried many different getpass style packages but they either didn't install properly or would't work. The code below has been adapted from getpass3. It requires the getch package and only runs under Python 3.

#/usr/bin/env python3

from getch import *
import sys

echo = '*'

def getpass(label):
    print(label, end='', flush=True)

    password = ''

    while True:
        inp = getch()

        if inp == '\n':
            break
        elif inp == '\003':
            raise KeyboardInterrupt
        elif inp == '\04':
            raise EOFError
        else:
            print(echo, end='', flush=True)
            password += inp

    print('')

    return password

print(getpass("Password: "))
@sujaldev
Copy link

You could add python after the first three backticks to enable syntax highlighting

print("syntax highlighting")

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