Communication with the USB device in Python

Communication with the USB device in Python

Assuming your using Linux and libusb-1.0 as a PyUSBs backend library.

According to the libusb documentation:

// Detach a kernel driver from an interface.
// If successful, you will then be able to claim the interface and perform I/O.
int libusb_detach_kernel_driver (libusb_device_handle *dev, 
                                 int interface_number)  

// Re-attach an interfaces kernel driver, which was previously 
// detached using libusb_detach_kernel_driver().
int libusb_attach_kernel_driver(libusb_device_handle *dev,
                                int interface_number)

So basically, you need to call detach_kernel_driver first to detach already attached kernel driver (if any) from the devices interface, so you can communicate with it in your code (its either your code or some kernel driver talking to the devices interface). When youre done, you may want to call attach_kernel_driver to re-attach the kernel driver again.

I believe theres no need to call any of those C functions/Python methods if you can ensure that no kernel driver is loaded for a given device (or manually unload it before running your code).


I just got this piece of code (based on your sample) working. Note: for simplicity Ive hardcoded 0 as interface number for detach_kernel_driver and attach_kernel_driver – you should make it smarter, I suppose.

import usb

dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)

reattach = False
if dev.is_kernel_driver_active(0):
    reattach = True

cfg = dev.get_active_configuration() 

interface_number = cfg[(0,0)].bInterfaceNumber 
alternate_settting = usb.control.get_interface(dev, interface_number) 
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = interface_number, 
                            bAlternateSetting = alternate_settting) 

ep = usb.util.find_descriptor(intf,custom_match = 
      lambda e: 
    usb.util.endpoint_direction(e.bEndpointAddress) == 

# This is needed to release interface, otherwise attach_kernel_driver fails 
# due to Resource busy

# It may raise USBError if theres e.g. no kernel driver loaded at all
if reattach:

Communication with the USB device in Python

Leave a Reply

Your email address will not be published. Required fields are marked *