How to flush the input stream?

From Rosetta Code

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)

The try part is for Windows platform. I have not personally tested this part. But the except section works on linux terminal. termios module has some terminal interface functions. the tcflush can flush input or output buffered data. This part definitely works in my tests.

Leave a Comment