Python usb detection

霸气de小男生 提交于 2019-11-30 10:06:08

I use this to check attached USB devices:

Requirements

  • pyusb

Example

import usb
from usb.core import USBError

### Some auxiliary functions ###
def _clean_str(s):
    '''
    Filter string to allow only alphanumeric chars and spaces

    @param s: string
    @return: string
    '''

    return ''.join([c for c in s if c.isalnum() or c in {' '}])


def _get_dev_string_info(device):
    '''
    Human readable device's info

    @return: string
    '''

    try:
        str_info = _clean_str(usb.util.get_string(device, 256, 2))
        str_info += ' ' + _clean_str(usb.util.get_string(device, 256, 3))
        return str_info
    except USBError:
        return str_info


def get_usb_devices():
    '''
    Get USB devices

    @return: list of tuples (dev_idVendor, dev_idProduct, dev_name)
    '''

    return [(device.idVendor, device.idProduct, _get_dev_string_info(device)) 
                for device in usb.core.find(find_all=True)
                    if device.idProduct > 2]

I hope it helps! I have some more code related to USB stuff here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!