【笔记】Python3操作USB

前言

Python3操作USB

准备工作

  • 安装libusb环境

手动编译

1
2
apt-get install libusb-1.0-0-dev
apt-get install libusb-dev

下载依赖

1
pip3 install pyusb

引入依赖

1
import usb.core

获取指定USB的VID和PID

1
lsusb -v

操作USB

main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
dev = usb.core.find(idVendor=0x09c5, idProduct=0x0668)
if dev is None:
raise ValueError('Device not found')
print(dev)

# 输入端点
endpoint_in = dev[0].interfaces()[0].endpoints()[0].bEndpointAddress
# 输出端点
endpoint_out = dev[0].interfaces()[0].endpoints()[1].bEndpointAddress

index = dev[0].interfaces()[0].bInterfaceNumber
dev.reset()
if dev.is_kernel_driver_active(index):
dev.detach_kernel_driver(index)

def rx_loop():
while True:
try:
data = dev.read(endpoint_out, 512)
print(data)
except Exception as e:
print(e)

def tx_loop():
while True:
try:
data = dev.write(endpoint_in, "", 1000)
print(data)
except Exception as e:
print(e)

  • 由于操作系统底层接口,所以需要root权限运行程序
1
sudo python3 main.py

完成

参考文献

CSDN——作恶的土豆
stackoverflow——Akliph