By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,772 Members | 919 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,772 IT Pros & Developers. It's quick & easy.

Flushing standard input

P: n/a
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
Oct 18 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
I found this.
http://mail.python.org/pipermail/pyt...er/359296.html

You cannot flush input. The flush method only relates to output. The
*other* side of the file has to flush *its* output in order for you to
see it as input.

Oct 18 '06 #2

P: n/a
At Wednesday 18/10/2006 16:45, Fabian Steiner wrote:
>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

Oct 18 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.