检查快速输入?

Check for Rapid Inputs?

标题描述性不强;我不确定如何描述我的问题。在我的 Python 代码中,我有一个检测键输入的侦听器和 returns 一个输出。为了简单起见,假设输出是打印和哔声。我不希望它同时检测到太多按键并发出太多哔哔声。因此,在每次输入时,我想在继续之前检查是否有最近的输入。如果在最后一秒已经有输入,它将跳过输出。这是我当前的代码:

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()

我不是 Python 专家。我试过使用以下代码,但它不起作用:

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()

我很确定我需要以某种方式在这里使用 global,但我不确定如何使用。我尝试时总是出错。

我总是避免使用 global 关键字,所以我会做的是使用可变数据类型并更新内容。

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()

如果您喜欢它现在的样子,那么您只需在更新变量值之前添加 global。例如:

global last_input = time.time()