1

I'm experiencing a problem with input(). I've a program like:

while condition:
    do_stuff()
value = input("Insert data >> ")

If I write something while the loop is executing, when condition becomes False and input() is executed, Insert data >> something is printed on the CLI.

How can I prevent something from being printed? Is there a method to flush the input stream before calling input()?

mik3.rizzo
  • 65
  • 7
  • 1
    This is called typeahead and provided (usually) by the underlying readine. Does reading from stdin before the input call fix it? – 2e0byo Oct 16 '22 at 16:05
  • 2
    Also, are you sure you want to disable this? It's usually thought of as a feature for users who know what's coming next. – 2e0byo Oct 16 '22 at 16:07
  • 1
    I tried to sys.stdin.read() and readline() before, but without success. Yes, I want to cancel all the data accidentally inserted before the input() statement! – mik3.rizzo Oct 16 '22 at 16:09
  • 1
    The easiest way to do that is to do a non-blocking read before calling `input()`, to consume everything in the buffer and throw it away. But you _will_ annoy users by doing this -- it breaks any ability to feed your program's stdin from a file or a heredoc or anything else that provides all the input up-front. – Charles Duffy Oct 16 '22 at 16:24
  • Thanks. If I make a read before input() it will consume also the input()'s message... – mik3.rizzo Oct 16 '22 at 16:39
  • 1
    https://stackoverflow.com/questions/21791621/taking-input-from-sys-stdin-non-blocking may be relevant. – 2e0byo Oct 16 '22 at 18:11
  • I'll have a look, thanks. – mik3.rizzo Oct 16 '22 at 18:34

0 Answers0