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

如何在Python单循环中无阻塞读取键盘并追踪鼠标(无需线程)

无线程实现鼠标键盘同循环追踪的方案

可以不开启线程实现需求,下面是具体可行方案:

使用pynput库实现

pynput支持无阻塞的全局键盘监听,同时能在主循环中同步获取鼠标位置,无需手动创建额外线程:

from pynput.mouse import Controller
from pynput.keyboard import Listener, Key

# 初始化鼠标控制器
mouse = Controller()
# 存储当前按下的按键
current_key = None

# 按键按下回调
def on_press(key):
    global current_key
    current_key = key

# 按键释放回调
def on_release(key):
    global current_key
    current_key = None

# 启动键盘监听(后台非阻塞运行)
listener = Listener(on_press=on_press, on_release=on_release)
listener.start()

# 主循环同时追踪鼠标和键盘
while True:
    # 获取并打印鼠标位置
    mouse_x, mouse_y = mouse.position
    print(f"The mouse position is: {mouse_x}, {mouse_y}")
    
    # 打印当前按下的按键
    if current_key is not None:
        try:
            # 普通字符按键
            print(f"{current_key.char} is down")
        except AttributeError:
            # 特殊按键(如Shift、Ctrl等)
            print(f"{current_key} is down")

关于你遇到的问题说明

  • msvcrt模块:kbhit()仅对控制台程序的本地输入有效,不支持全局键盘监听,且对特殊按键兼容性差,所以会出现返回0的情况,不适合你的场景需求。
  • keyboard模块:它并非只能监听特定按键,可通过keyboard.is_pressed()配合循环检测所有按键,但pynput的回调式监听更简洁稳定,无需在循环中轮询所有按键状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:15:32