WSL2 中 pynput 无法捕获按键输入?

视频链接:https://www.bilibili.com/video/BV1vCmiB1ENV/?vd_source=5ba34935b7845cd15c65ef62c64ba82f

你是否遇到过在 WSL2 中,pynput 无响应,无法捕获键盘的输入?

WSL2 本质是 Linux 内核子系统,无法直接访问 Windows 的硬件输入,通过输入 ls /dev 发现实际是没有 input,这里有两种方式:

  1. 通过 usb 重定向给 WSL2 也可以实现,比如之前用过的 WSL USB Manager 工具
  1. Linux 下的 pynput 依赖 X11/Xorg(显示服务器)实现全局键盘监听,无 GUI 环境(X Server)时,pynput 无法注册 / 捕获任何键盘事件,所以随便创建一个 X11 显示窗口即可

    import threading
    import tkinter as tk

    def startGui():
    root = tk.Tk()
    root.title("WSL2 X11 Bridge")
    root.geometry("1x1")
    root.iconify()
    root.mainloop()

    def runGuiThread():
    gui_thread = threading.Thread(target=startGui, daemon=True)
    gui_thread.start()

完整测试代码如下:

复制代码
from pynput import keyboard
import time

class KeyListener:
    def __init__(self, key_states, callbackFunc=None):
        self.listener = keyboard.Listener(on_press=self.onPress, on_release=self.onRelease)
        self.key_states = key_states
        self.callbackFunc = callbackFunc

    def join(self):
        self.listener.join()

    def start(self):
        self.listener.start()

    def stop(self):
        self.listener.stop()

    def onPress(self, key):
        if key in self.key_states:
            self.key_states[key] = True

        if key == keyboard.Key.esc:
            return False

    def onRelease(self, key):
        if key in self.key_states:
            self.key_states[key] = False

    def callbackFunc(self):
        pass

def test_callback():
    print('test_callback')

if __name__ == '__main__':
    key_states = {
        keyboard.Key.up: False,
        keyboard.Key.down: False,
        keyboard.Key.left: False,
        keyboard.Key.right: False,
        keyboard.Key.alt_l: False,
        keyboard.Key.alt_r: False,
    }
    key_listener = KeyListener(key_states, callbackFunc=test_callback)
    key_listener.start()

    import threading,tkinter as tk
    def startGui():
        root = tk.Tk()
        root.title("WSL2 X11 Bridge")
        root.geometry("1x1")
        root.iconify()
        root.mainloop()

    def runGuiThread():
        gui_thread = threading.Thread(target=startGui, daemon=True)
        gui_thread.start()

    runGuiThread()

    while True:
        if key_states[keyboard.Key.up]:
            print('up')
        if key_states[keyboard.Key.down]:
            print('down')
        if key_states[keyboard.Key.left]:
            print('left')
        if key_states[keyboard.Key.right]:
            print('right')
        if key_states[keyboard.Key.alt_l]:
            print('alt_l')
        if key_states[keyboard.Key.alt_r]:
            print('alt_r')
        time.sleep(0.01)
    key_listener.join() 
相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github