Linux:python:在raw_input()之前清除input缓冲区

我已经看了一些关于这个的线程,但似乎并没有解决我的问题。 我正在运行linux,当我使用raw_input(),并在每个之间暂停时,它将采取我以前按的数据,这里是一个例子:

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") 

如果我在5秒钟之后按下任意键后input,则另外两个原始input将接受input。 我希望能够刷新数据,并让用户得到提示。

谢谢。

对于Unix,你可以使用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,队列)

丢弃文件描述符fd上的排队数据。 队列选择器指定哪个队列:输入队列的TCIFLUSH,输出队列的TCOFLUSH,或者两个队列的TCIOFLUSH。

使用tty(linux)和msvcrt(windows)的keypress getch类并使用sys.stdout.flush()函数来刷新缓冲区