这个试了不行 , 有没其他方法
时间: 2024-01-16 11:05:03 浏览: 27
如果使用 `pyudev` 库无法监听到 USB 设备的插拔事件,你可以尝试使用 `pyusb` 库。以下是一个简单的示例代码:
```python
import usb.core
import usb.util
# Find USB device
dev = usb.core.find(idVendor=0x12ab, idProduct=0x21ab)
# If the device is found
if dev is not None:
# Detach the kernel driver from the USB device
if dev.is_kernel_driver_active(0):
dev.detach_kernel_driver(0)
# Claim the USB device interface
usb.util.claim_interface(dev, 0)
# Continuously listen for USB events
while True:
try:
# Try to read data from the USB device
data = dev.read(1, 1000)
# If data is received, print it
print(data)
except usb.core.USBError as e:
# If no data is received, continue listening
pass
else:
print('Device not found')
```
这段代码会不断监听 USB 设备的数据,并在控制台输出相应的消息。你可以根据需要修改代码,实现更复杂的功能。请注意,这段代码需要你先安装 `pyusb` 库。