Search code examples
pythonpython-3.xinputbackspacegetch

Can Getch (or something similar) be made to accept backspaces?


I am using the following function, getPass() for a secure password entry:

def getPass():
    password = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        password += x
    return password

However, the one catch is that backspaces are not accepted except as new characters:

Backspaces in real life show up like this: ( "|" symbol used for reference)

Before:

••••|

After:

••• |

But when I execute getpass(), it shows up in the console like:

Before: ****|

and then you hit backspace, what should become

*** |

actually becomes

****|*

(Notice the extra star).

Perhaps I should just leave the solution as print('Type your password:\n(Backspace not accepted: Press Enter to redo)) putting the user into a loop, but this is very annoying to 21st century users.


Solution

  • I can use the standard getpass() module.

    from getpass import getpass
    def getPass():
        password = getpass.getpass('Enter Your Password\n>>>')
        return password
    password = getpass()