You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python keyboard模块单词监听器异常触发问题求助

问题排查与修复方案

核心问题1:回调函数错误调用

你在keyboard.register_word_listener里传的是enable(),这会直接执行enable函数,而不是把函数作为回调传入。程序启动时就会立刻把condition设为True,导致脚本自动激活,完全跳过了监听"enable"的逻辑。

核心问题2:重复注册监听

把register_word_listener放在while True循环里,每次循环都会重复注册一次监听,会导致大量重复的监听器,不仅浪费资源,还可能引发异常。

修复后的代码

import keyboard
import time
from win32com.client import Dispatch

enabled = False
timer = 1
condition = False
wsh = Dispatch("WScript.Shell")

def enable():
    global condition
    condition = True

# 只注册一次监听,放在循环外面
keyboard.register_word_listener("enable", enable, [" "])

while True:
    if condition:
        enabled = True

    if enabled:
        time.sleep(0.1)
        wsh.SendKeys("piss")
        time.sleep(0.1)
        wsh.SendKeys("{ENTER}")
        time.sleep(timer)

额外说明

  • 确保已安装依赖包:pip install keyboard pywin32
  • register_word_listener的第三个参数是触发单词的分隔符,[" "]表示输入"enable"后按空格才会触发,也可根据需要改成["\n"](回车)等
  • 若需要"disable"功能,可同理注册另一个单词监听器,将condition设为False

内容的提问来源于stack exchange,提问作者myNameSucks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:07:05