Flushing standard input

F

Fabian Steiner

Recently I came across a problem which I still can't solve on my own.
Consider this small example:

import sys
import time

time.sleep(3)
print
sys.stdin.flush()
input = raw_input('Your input: ')
print 'Your input: ', input

While the script is sleeping I type in the word 'test1', so that it is
printed on the console. Having slept for three seconds the script
continues and wants me to type in another word 'test2' and I hit return.

The output looks like this:

fabi@jupiter ~ [ 21:41:27 ] $ python test.py
test1
test2
Your input: test1test2

Is there any way to flush the stdin buffer so that 'test1' is _not_
regarded as input? How could one solve this issue?

Cheers,
Fabian
 
G

Gabriel Genellina

Recently I came across a problem which I still can't solve on my own.
Consider this small example:

import sys
import time

time.sleep(3)
print
sys.stdin.flush()
input = raw_input('Your input: ')
print 'Your input: ', input

While the script is sleeping I type in the word 'test1', so that it is
printed on the console. Having slept for three seconds the script
continues and wants me to type in another word 'test2' and I hit return.

The output looks like this:

fabi@jupiter ~ [ 21:41:27 ] $ python test.py
test1
test2
Your input: test1test2

Is there any way to flush the stdin buffer so that 'test1' is _not_
regarded as input? How could one solve this issue?

This works ONLY on Windows:

import sys
import time
from msvcrt import getch,kbhit

time.sleep(3)
while kbhit(): getch() # consume any pending keypresses
print
input = raw_input('Your input: ')
print 'Your input: ', input

For Unix you could look at the tty/termios modules. This recipe shows
a portable getch() function:
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892>


--
Gabriel Genellina
Softlab SRL





__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top