7

I have looked at a few thread about this, but it doesn't seem to solve my problem. I am running linux and when I use raw_input(), with a pause between each, it will take the data that I have pressed before, 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 the enter during the 5 seconds, the two other raw input will take the input. I would like to be able to flush the data and let the user be prompted.

thank you.

2 Answers 2

12

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)

Discard queued data on file descriptor fd. The queue selector specifies which queue: TCIFLUSH for the input queue, TCOFLUSH for the output queue, or TCIOFLUSH for both queues.

Sign up to request clarification or add additional context in comments.

1 Comment

I had a similar problem using the keyboard library and I've been struggling so much to find a solution. This still works 8 years later with Python 3.9, thank you!
3

Use keypress getch class of tty (linux) and msvcrt (windows) and use sys.stdout.flush() function to flush the buffer

2 Comments

tty doesn't appear to have this class on python2.7. I'm on ubuntu 14.04
for tty it is termios class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.