Reputation: 127
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
Upvotes: 5
Views: 1120
Reputation: 1651
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")
Upvotes: 2