Home > Back-end >  Check for Rapid Inputs?
Check for Rapid Inputs?

Time:05-20

The title isn't very descriptive; I wasn't sure how to describe my problem. In my Python code, I have a listener that detects key inputs and returns an output. For the sake of simplicity, let's say the output is a print and a beep sound. I don't want it to detect too many key presses at the same time and beep too much. So, on every input, I would like to check if there was a recent input before proceeding. If there was already an input in the last second, it will skip the output. Here is my current code:

from pynput.keyboard import Key, Listener
from playsound import playsound

def onInput(key):
    #HERE I NEED TO CHECK IF THERE WAS A RECENT INPUT, AND EXIT THE FUNCTION IF THERE WAS.
    print(str(key)   "' was pressed.")
    playsound("beep.mp3")

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

I'm not a Python expert. I have tried using the following code, but it doesn't work:

from pynput.keyboard import Key, Listener
from playsound import playsound
import time

lastInput = 0

def onInput(key):
    if time.time() - lastInput > 1:
        lastInput = time.time()
        return None
    lastInput = time.time()
    print(str(key)   "' was pressed.")
    playsound("beep.mp3")

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

I'm pretty sure I need to use global here somehow, but I'm not sure how. I keep getting errors when I try it.

CodePudding user response:

I always avoid using the global keyword, so what I would do is use a mutable data type and update the contents instead.

from pynput.keyboard import Key, Listener
from playsound import playsound
import time

times = {
    'last_input': 0
}

def onInput(key):
    if time.time() - times['last_input'] > 1:
        times["last_input"] = time.time()
        return None
    times['last_input'] = time.time()
    print(str(key)   "' was pressed.")
    playsound("beep.mp3")

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

If you prefer it the way it is then all you need is to add global before updating the variable's value. for example:

global last_input = time.time()
  • Related