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

使用Python+pywin32检测键盘VID、PID报错求助

解决Win32_Keyboard检测的WMI类名错误及优化方案

问题根源

报错pywintypes.com_error: (-2147217392, 'OLE error 0x80041010')的直接原因是你使用了错误的WMI类名:Win32_Keyboards(复数形式),正确的WMI键盘设备类名是**Win32_Keyboard**(单数)。WMI类名严格区分拼写和单复数,错误的类名会导致WMI无法定位到对应设备实例集合。

修正后的键盘检测脚本

同时,部分键盘设备可能不存在PNPDeviceID属性,直接访问会触发AttributeError,因此需要添加属性存在性检查。优化后的完整代码如下:

import re
import win32com.client
from colorama import Fore
import time

def list_keyboard_devices():
    wmi = win32com.client.GetObject("winmgmts:")
    # 修正为正确的WMI类名:Win32_Keyboard(单数)
    devices = wmi.InstancesOf("Win32_Keyboard")
    keyboard_list = []
    
    for device in devices:
        name = device.Name
        vid, pid = None, None
        # 先检查设备是否存在PNPDeviceID属性且不为空
        if hasattr(device, "PNPDeviceID") and device.PNPDeviceID:
            match = re.search(r'VID_(\w+)&PID_(\w+)', device.PNPDeviceID)
            if match:
                vid, pid = match.groups()
        keyboard_list.append((name, vid, pid))
 
    return keyboard_list

def select_keyboard_and_configure():
    print(Fore.CYAN + "\nDetecting keyboard devices...")
    keyboards = list_keyboard_devices()
 
    if not keyboards:
        print(Fore.RED + "No keyboard devices found. Exiting...")
        time.sleep(5)
        exit()
    # 格式化输出检测到的键盘信息
    for idx, (name, vid, pid) in enumerate(keyboards, 1):
        vid_str = vid if vid else "Not found"
        pid_str = pid if pid else "Not found"
        print(f"{idx} → {name}\tVID: {vid_str}, PID: {pid_str}")
    # 后续选择逻辑可在此补充
    selected_num = int(input("Select your keyboard number: "))
    # ... 其他配置代码

额外优化建议

  • 添加COM异常捕获:遍历WMI实例时可以捕获pywintypes.com_error,避免因个别设备异常导致脚本崩溃
  • 过滤冗余设备:可通过DeviceID或Description字段过滤虚拟键盘、系统内置键盘等非目标设备
  • 统一检测逻辑:封装通用WMI设备检测函数,减少鼠标、键盘检测代码的重复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:30:37