Python Hid庫安裝方法


最近用弄一個USB HID,無奈USB調試工具很少,那就自己動手寫一個,人生苦短,我用Python,Python操作USBHID接口需要用到HID庫,為了安裝這個庫,走了不少彎路,踩了不少坑,完成后記錄下來,分享給大家,也給自己留個筆記。

先按照常規操作,直接使用pip install hid,可以安裝成功,但無法使用,import hid時會提示:

>>> import hid
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python\lib\site-packages\hid\__init__.py", line 30, in <module>
    raise ImportError(error)
ImportError: Unable to load any of the following libraries:libhidapi-hidraw.so libhidapi-hidraw.so.0 libhidapi-libusb.so libhidapi-libusb.so.0 libhidapi-iohidmanager.so libhidapi-iohidmanager.so.0 libhidapi.dylib hidapi.dll libhidapi-0.d

無法使用,提示找不到一堆庫,再仔細看一下PyPI文檔,很明確,說是這個庫要依賴於hidapi庫。

image-20220418162212252

那就按照他的方法做吧:

image-20220418162236538

但下載下來就這三個文件,在網上找了半天也沒找到安裝方法,如果哪位大神知道,麻煩指點一下。

image-20220418162305900

但天無絕人之路,編譯好的安裝不了,那就試試源碼安裝吧,找到hidapi的源碼目錄:https://github.com/libusb/hidapi

image-20220418162315805

並且點那個綠色的code按鈕,復制git地址,在電腦上新建一個空目錄,使用git clone命令把這個代碼拉下來。

image-20220418162324206

然鵝,這並沒有什么卵用!源碼是C++的,還是好好學C++ 吧!而且編譯出來估計還是上面那幾個dll。

但life is short,you need python,作為一名愛鑽研的程序員,則能這么放棄,經過我不懈努力,終於找到正確的方法:

既然是Python語言,那就得安裝Pyhton的hidapi庫。。。

回想起來前面的hidapi庫,在PyPI上找到這個:

image-20220418162333834

先試試 pip install hidapi:

pip install hidapi
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting hidapi
  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/ce/f0/7140fda56ebbc7ef47a3589da4938d76b17c930ce5c1187d247f7b11bdcf/hidapi-0.11.2-cp39-cp39-win_amd64.whl (55 kB)
Requirement already satisfied: setuptools>=19.0 in c:\python\lib\site-packages (from hidapi) (49.2.1)
Installing collected packages: hidapi
Successfully installed hidapi-0.11.2

可以安裝成功,但是問題依舊,沒有一點改善。。。

那再試試源碼安裝:

  1. 下載源碼:
$ git clone https://github.com/trezor/cython-hidapi.git  
$ cd  cython-hidapi    
  1. 初始化子模塊:
$  git submodule update --init    
  1. 編譯:
$  python setup.py build    
  1. 安裝:
$python  setup.py install   
  1. 用pip本地安裝
$  pip install -e .  
  1. 測試一下:
$  python  
>>>  import hid  
>>>     
  1. 跑一下自帶的例子:
$  python try.py  

Oyeah,終於成功了,趕快跑一下自己的工程,然鵝。。。 算了,放棄吧。但又不甘心,覺得樣例工程都能跑,自己的工程卻不能,肯定是還少點火候,應該也就差一點點了。

原來樣例工程目錄下有一個hid.py的文件,運行樣例工程的時候,導入的是這個文件,而在其他地方運行的是庫里面的hid,但剛才明明已經用pip把源碼給安裝了,肯定是哪里沖突了,對,就是之前pip install hid那個,把它卸載了:

  pip  uninstall hid  
  Found  existing installation: hid 1.0.5  Uninstalling  hid-1.0.5:   Would remove:      c:\python\lib\site-packages\hid-1.0.5.dist-info\*    c:\python\lib\site-packages\hid\*  Proceed  (Y/n)? y  

 Successfully uninstalled hid-1.0.5  

到此,問題終於解決,順便分享一下我用python寫的HID調試工具:

image-20220421165528623


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM