Linux: python: flush input buffer to raw_input ()

I looked through several threads about this, but it doesn't seem to solve my problem. I run linux, and when I use raw_input (), with a pause between them, it will receive the data I clicked earlier, here is an example:

 import time
 a = raw_input("first input")
 b = raw_input("second input")
 time.sleep(5)
 #flush junk?
 a = raw_input("third input")
 b = raw_input("fourth input")

if I press any keys followed by input within 5 seconds, the second input signal will be input. I would like to be able to reset the data and give the user a request.

thank.

+4
source share
2 answers

For unix you can use termios.tcflush

from termios import tcflush, TCIFLUSH
import time,sys

a = raw_input("first input ")
b = raw_input("second input ")

time.sleep(5)
tcflush(sys.stdin, TCIFLUSH)

a = raw_input("third input ")
b = raw_input("fourth input ")

~$ python foo.py 
first input 1
second input 2
33
33
third input 3
fourth input 4

termios.tcflush (fd, queue)

fd. , : TCIFLUSH , TCOFLUSH TCIOFLUSH .

+3

keypress getch tty (linux) msvcrt (windows) sys.stdout.flush()

+3

All Articles