0

I'm writing a Python script in which at a certain point, the user is asked to enter a key combination (by simultaneously pressing those keys) and to confirm with enter. Grabbing the key combination and the enter key is done using the keyboard module and thus it works whether the command line is in focus or not. After that, an input() prompt is shown in which they need to enter some text.

The problem is that this input prompt gets 'skipped'. I assume this is because there are some characters and an enter stored which get entered into the input as soon as it appears.

How could I fix this? There's an os.system('cls') before the input, but that doesn't help. I've also tried adding a throwaway input() before the main prompt, this sort of worked but I'm looking for more of a general solution that also works if the characters aren't followed by an enter.

Cedric
  • 245
  • 1
  • 12

1 Answers1

0

Found it, looks like I wasn't using the correct search term. This function clears the input buffer on both Windows and UNIX:

def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios    #for linux/unix
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)

Source

Since I'm already importing the module at the top of my file and I only need Windows support for now, this is what I'm using:

def flush_input():
    while msvcrt.kbhit():
        msvcrt.getch()
Cedric
  • 245
  • 1
  • 12