'Check for Rapid Inputs?

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source