You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

已安装hidapi仍触发ModuleNotFoundError的技术求助

问题描述

我尝试运行以下代码读取HID设备:

import hidapi

# Find the device
devices = hidapi.DeviceManager().devices()
for device in devices:
    if device.vendor_id == 0x2341 and device.product_id == 0x0042:
        gamepad = device
        break

# Read data from the device
data = gamepad.read(64)
print(data)

已通过pip3 install hidapi成功安装模块,但运行代码时仍提示ModuleNotFoundError: No module named 'hidapi',命令行操作记录如下:

PS C:\Users\felix\OneDrive\Desktop\UE5 Space Ship Project> pip3 install hidapi
Defaulting to user installation because normal site-packages is not writeable
Collecting hidapi
  Using cached hidapi-0.14.0.post4-cp312-cp312-win_amd64.whl.metadata (3.7 kB)
Requirement already satisfied: setuptools>=19.0 in c:\python312\lib\site-packages (from hidapi) (75.6.0)
Using cached hidapi-0.14.0.post4-cp312-cp312-win_amd64.whl (70 kB)
Installing collected packages: hidapi
Successfully installed hidapi-0.14.0.post4
PS C:\Users\felix\OneDrive\Desktop\UE5 Space Ship Project> python -u "c:\Users\felix\OneDrive\Desktop\UE5 Space Ship Project\HID_test.py"
Traceback (most recent call last):
  File "c:\Users\felix\OneDrive\Desktop\UE5 Space Ship Project\HID_test.py", line 1, in <module>
    import hidapi
ModuleNotFoundError: No module named 'hidapi'
PS C:\Users\felix\OneDrive\Desktop\UE5 Space Ship Project>

运行环境:Windows 11、Python 3.12.6

解决方案
  • 确认Python与pip的对应关系
    问题大概率是pip3安装的模块和python命令调用的解释器不是同一个版本。执行以下命令检查版本是否一致:

    python --version
    pip3 --version
    

    如果版本不匹配,改用python -m pip install hidapi安装模块,这会确保模块安装到当前python命令对应的解释器环境中。

  • 验证模块安装路径
    Windows下用户级安装的模块默认路径为C:\Users\felix\AppData\Roaming\Python\Python312\site-packages,检查该目录下是否存在hidapi相关文件。
    也可以在代码开头添加以下内容,查看Python加载模块的路径列表,确认是否包含上述用户目录:

    import sys
    print(sys.path)
    

    如果路径中没有用户目录,可手动添加:

    import sys
    sys.path.append(r'C:\Users\felix\AppData\Roaming\Python\Python312\site-packages')
    import hidapi
    
  • 使用Python完整路径运行
    直接调用Python安装目录下的python.exe运行脚本,确保使用的是安装了hidapi的解释器:

    C:\Python312\python.exe "c:\Users\felix\OneDrive\Desktop\UE5 Space Ship Project\HID_test.py"
    
  • 检查虚拟环境
    如果当前项目使用了虚拟环境,需要先激活虚拟环境,再重新安装hidapi并运行脚本。

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

火山引擎 最新活动