问题
I'm having a code with a loop asking for some input and then sleeps for some time. The purpose is to prevent for human errors, forcing the user to wait before entering the next input. The problem is, that python does not ignore the keyboard inputs while time.sleep.
Here is an example code:
from time import sleep
from msvcrt import getch
for i in range(3):
print 'Enter a character'
char = getch()
sleep(2)
print char
When pressing some characters consecutively during time.sleep(), msvcrt.getch() remembers them and the loop runs to the end. I want that every character pressed during sleep will be ignored. How can I do that?
回答1:
Sorry for wrong answer that i have posted before(as i have deleted though), it is the human level problem that you are asking for.
The program thread is the only event that is put on to sleep, while the keyboard process is still running obviously it will record all the inputs and type after resuming from sleep.
This can't be achieved in this fashion
回答2:
This is an OS dependant issue, for windows i use this:
import msvcrt import time time.sleep(4) while msvcrt.kbhit(): flush = input() entry = input("Press enter!")
it just catches all the inputs before asking user for a new input, hope it helps!
来源:https://stackoverflow.com/questions/48034297/ignore-keyboard-input-in-python-while-sleeping