How clear stdin in Python

Question:

I would like to know if can be cleared the stdin after some key has been entered.
I am doing an input timeout following a response from this forum like this one:

 while True:
    web_scrapping()    
    print ("Press ENTER: n")
    time.sleep(interval)
    i, o, e = select.select( [sys.stdin], [], [], 10 )
    if (i):
        Start()

If works ok, check if some keystroke has been pressed and in case it does goes to the fuction Start().
But my problem is that Start() also has an input question, so the previous keystroke from the While True also transmit to the Start(), so the result is that the input question in Start() showes twice because the previous keystroke.
So I would like to clear that keystroke before goes to Start(). Is that possible?
Thanks

Asked By: macbeto

||

Answers:

This is a good one, I believe that if you’re working on a UNIX system you should be able to clear any queued data in stdin before calling input using termios. Try something like this:

from termios import tcflush, TCIFLUSH

while True:
    web_scraping()
    print ("Press ENTER: n")
    time.sleep(interval)
    i, o, e = select.select( [sys.stdin], [], [], 10 )
    if (i):
        # Clear queue before asking for new input
        tcflush(sys.stdin, TCIFLUSH)
        Start()

This should make possible to have a fresh queue when calling Start. Commenting line 13 from the example below will call input submitting whatever is found in the queue at call time. Flushing the queue before the call helps to avoid that behavior:

import select
import sys
import time
from termios import TCIFLUSH, tcflush

while True:
    print("Pretend I'm doing some stuff")
    time.sleep(2)
    i, o, e = select.select([sys.stdin], [], [], 2)
    # Enters if anything has been submitted
    if i:
        # Clear queue before asking for new input
        #   commenting it will submit whathever data is queued to stdin
        tcflush(sys.stdin, TCIFLUSH)
        a = input("Echo: ")
        print(f"your input is: {a}")
        break
    else:
        print("Nothing found in stdin")

Answered By: anddt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.