我想监听键盘快捷键ESC + ESC,然后运行一些代码.我的意思是,如果用户按两次ESC键,那么应该会执行一些代码.

我try 了以下代码,但它不起作用:

from pynput import keyboard

pressed = set()

def run(s):
    if (s == "switch"):
        print("Hello World!")

def on_press(key):
    pressed.add(key)
    print(pressed)
    if (pressed == 27):
        print("Hello World!")

def on_release(key):
    if key in pressed:
        pressed.remove(key)

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

请帮助我使用最适合我的图书馆.

推荐答案

import time

from pynput import keyboard


class DoubleEscapeListener:
    def __init__(self):
        self.pressed = set()
        self.last_esc_time = 0
        self.double_press_threshold = 0.5  # Time within which two ESC keys must be pressed.

    def run(self):
        print("Hello World!")

    def on_press(self, key):
        if key == keyboard.Key.esc:
            current_time = time.time()
            if current_time - self.last_esc_time < self.double_press_threshold:
                self.run()
            self.last_esc_time = current_time

    def on_release(self, key):
        if key in self.pressed:
            self.pressed.remove(key)

    def listen(self):
        with keyboard.Listener(on_press=self.on_press, on_release=self.on_release) as listener:
            listener.join()


if __name__ == "__main__":
    listener = DoubleEscapeListener()
    listener.listen()

当在double_press_threshold时间内按两次ESC键时,此代码将运行run方法.您可以根据需要调整此阈值.

Python相关问答推荐

使用decorator 重复超载

在Python中,如何才能/应该使用decorator 来实现函数多态性?

避免循环的最佳方法

inspect_asm不给出输出

在Windows上启动新Python项目的正确步骤顺序

DuckDB将蜂巢分区插入拼花文件

跟踪我已从数组中 Select 的样本的最有效方法

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

比较两个二元组列表,NP.isin

根据条件将新值添加到下面的行或下面新创建的行中

时间序列分解

如何在Windows上用Python提取名称中带有逗号的文件?

scikit-learn导入无法导入名称METRIC_MAPPING64'

如何记录脚本输出

用合并列替换现有列并重命名

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

在pandas/python中计数嵌套类别

ConversationalRetrivalChain引发键错误

替换现有列名中的字符,而不创建新列

交替字符串位置的正则表达式