How to clear keyboard event buffer pynput.keyboard

Viewed 923

I have a function that is called on_press. However, if the user constantly hits the key the keyboard event buffer queue gets really large and my function (which takes a few hundreds of ms) gets called even after the user has stopped pressing the key. How can I solve this issue?

from pynput import keyboard

def f1():
    print("starting f1()..")
    # f1 takes time to finish

def on_press(key):
    print("pressed some key")
    f1()

with keyboard.Listener(on_press=on_press) as listener:
    listener.join()
3 Answers

You could create a thread or process to achieve that,If you want to use thread, like this below:

from pynput import keyboard
import threading, time


def task():
    time.sleep(3)  # Simulate the time of cost
    print("task  finish")


def f1():
    print("starting task..")
    # f1 takes time to finish
    # create a thread to execute the task.
    threading.Thread(target=task).start()


def on_press(key):
    print("pressed some key")
    f1()


with keyboard.Listener(on_press=on_press) as listener:
    listener.join()

For sure, you could reduce the amount of functions,just for easy to understand, so I define 3 functions.

You can create a queue to store the incoming keyboard keys and only add to it when it is empty like so:

from pynput import keyboard
from queue import Queue

queue = Queue()

def on_press(key):
    if queue.empty():
        queue.put(key)

listener = keyboard.Listener(on_press=on_press)
listener.start()

while True:
    key = queue.get()
    f1()
Related