1

I got a cool code can detect new USB plug-in, I want to extract idVendor and idProduct only, below is original function and my tried function.

I read through the question How can I extract all values from a dictionary in Python? before, but my situation seems slightly different.

  • original function
import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1


def info_usb_device(dev):
    xdev = find(idVendor=dev.idVendor, idProduct=dev.idProduct)
    if xdev.bDeviceClass == 9:  # don't list HUBs, see [USB class-codes](https://www.usb.org/defined-class-codes)
        return
    if xdev._manufacturer is None:
        xdev._manufacturer = get_string(xdev, xdev.iManufacturer, langid=1033)
    if xdev._product is None:
        xdev._product = get_string(xdev, xdev.iProduct, langid=1033)
    device_info = '[%20s] %8d %9d %s - %s' % (xdev.serial_number, dev.idVendor, dev.idProduct,
                                 str(xdev._manufacturer).strip(),
                                 str(xdev._product).strip())
    return (xdev.serial_number, device_info)


def add_usb_devices(device_dict):
    new_devices = []
    for bus in usb.busses():
        for dev in bus.devices:
            if dev is None:
                continue
            serial_info = info_usb_device(dev)
            if serial_info is not None:
                (serial, info) = serial_info
                if serial not in device_dict:
                    new_devices.append(serial)
                    device_dict[serial] = info
    return new_devices


if __name__ == "__main__":
    device_dict = {}
    print('%22s %8s %9s %s' % ('serial', 'idVendor', 'idProduct', 'Manufacturer - Product'))
    print('-'*22, '-'*8,  '-'*9, '-'*30)
    # first scan
    add_usb_devices(device_dict)
    for device_info in device_dict.values():
        print(device_info)
    # next scans
    for i in range(5):  # run 5 more scans 
        new_serials = add_usb_devices(device_dict)
        if len(new_serials) > 0:
           print('** (scan %d) FOUND NEW USB DEVICES/SERIALS: %s' % (i, new_serials))
           for serial in new_serials:
               print(device_dict[serial])
        time.sleep(7)  # waiting 3 seconds before new scan
    print('Scans completed.')
  • output for all USB connection and new USB
serial idVendor idProduct Manufacturer - Product
---------------------- -------- --------- ------------------------------
[                None]     1133     49271 Logitech - USB Optical Mouse  
[             2004888]     1423     37728  - USB Reader  
[    4234ICZMDJF5MWAK]    34148      4096 JetFlash - Mass Storage Device  
[5334354E373539325A315A4B]     5117      2112 Generic - External       
** (scan 2) FOUND NEW USB DEVICES/SERIALS: ['00000000000031']  
[      00000000000031]     4871       357 USBest Technology - USB Mass Storage Device  
Scans completed.
  • tried function(to extract idVendor and idProduct only) I tried to split and list device_dict[serial] and the list[1], list[2] could be the one I want but seems not correct.

import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1
from dateutil import parser

def info_usb_device(dev):
    xdev = find(idVendor=dev.idVendor, idProduct=dev.idProduct)
    if xdev.bDeviceClass == 9:  # don't list HUBs, see [USB class-codes](https://www.usb.org/defined-class-codes)
        return
    if xdev._manufacturer is None:
        xdev._manufacturer = get_string(xdev, xdev.iManufacturer, langid=1033)
    if xdev._product is None:
        xdev._product = get_string(xdev, xdev.iProduct, langid=1033)
    device_info = '[%20s] %8d %9d %s - %s' % (xdev.serial_number, dev.idVendor, dev.idProduct,
                                 str(xdev._manufacturer).strip(),
                                 str(xdev._product).strip())
    return (xdev.serial_number, device_info)


def add_usb_devices(device_dict):
    new_devices = []
    for bus in usb.busses():
        for dev in bus.devices:
            if dev is None:
                continue
            serial_info = info_usb_device(dev)
            if serial_info is not None:
                (serial, info) = serial_info
                if serial not in device_dict:
                    new_devices.append(serial)
                    device_dict[serial] = info
    return new_devices


if __name__ == "__main__":
    device_dict = {}
    print('%22s %8s %9s %s' % ('serial', 'idVendor', 'idProduct', 'Manufacturer - Product'))
    print('-'*22, '-'*8,  '-'*9, '-'*30)
    # first scan
    add_usb_devices(device_dict)
    for device_info in device_dict.values():
        print(device_info)
    # next scans
    for i in range(5):  # run 5 more scans 
        new_serials = add_usb_devices(device_dict)
        if len(new_serials) > 0:
           print('** (scan %d) FOUND NEW USB DEVICES/SERIALS: %s' % (i, new_serials))
           for serial in new_serials:
               print(device_dict[serial])
        time.sleep(4)  # waiting 3 seconds before new scan
    
    str_device_dict_serial = {} 

    str_device_dict_serial = device_dict[serial]
    #splited_str_device_dict_serial= str_device_dict_serial.split(" ")
    
    #list_splited_str_device_dict_serial = list(splited_str_device_dict_serial)
    
    print('Scans completed.')


    print("+  +  +  +  +  +  +")
    print(device_dict[serial])
    print(type(device_dict[serial]))
    
  
    
    print("+ + + +")

    print(str_device_dict_serial)
    print(type(str_device_dict_serial))
Barmar
  • 741,623
  • 53
  • 500
  • 612
j ton
  • 229
  • 9
  • The code that calls `split()` is commented out. Please post the actual code. – Barmar Oct 04 '22 at 04:08
  • `str_device_dict_serial = device_dict[serial]` is not inside the `for serial in new_serials:` loop. So it uses the value of `serial` from the last iteration of that loop. – Barmar Oct 04 '22 at 04:09
  • i see, thanks @Barmar, I have some clue now, let me try then – j ton Oct 04 '22 at 05:42
  • sorry, I am stock again, so even I return `device_dict[serial]` from `def add_usb_devices()` , the `str_device_dict_serial = device_dict[serial]` still not work – j ton Oct 04 '22 at 05:52
  • I don't really understand most of this code, since I have no idea what any of the xdev stuff does. That was just an obvious problem. – Barmar Oct 04 '22 at 05:59
  • xdev means extend device of name, store the value `idVendor` and `idProduct` , xdev just name anyway – j ton Oct 04 '22 at 06:13

1 Answers1

0
  • regular expression string number only

import re
AAA = "[ 01DZTW5EXY5TSUF8] 34148 4096 JetFlash - Mass Storage Device"

BBB = re.findall(r'\b\d+\b', AAA)

then use this concept with the string want to extract

  • solved code based on offered:

import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1
import re

def info_usb_device(dev):
    xdev = find(idVendor=dev.idVendor, idProduct=dev.idProduct)
    if xdev.bDeviceClass == 9:  # don't list HUBs, see [USB class-codes](https://www.usb.org/defined-class-codes)
        return
    if xdev._manufacturer is None:
        xdev._manufacturer = get_string(xdev, xdev.iManufacturer, langid=1033)
    if xdev._product is None:
        xdev._product = get_string(xdev, xdev.iProduct, langid=1033)
    device_info = '[%20s] %8d %9d %s - %s' % (xdev.serial_number, dev.idVendor, dev.idProduct,
                                 str(xdev._manufacturer).strip(),
                                 str(xdev._product).strip())
    return xdev.serial_number, device_info 


def add_usb_devices(device_dict):
    new_devices = []
    for bus in usb.busses():
        for dev in bus.devices:
            if dev is None:
                continue
            serial_info = info_usb_device(dev)
            if serial_info is not None:
                (serial, info) = serial_info
                if serial not in device_dict:
                    new_devices.append(serial)
                    device_dict[serial] = info
    return new_devices


if __name__ == "__main__":
    device_dict = {}
    print('%22s %8s %9s %s' % ('serial', 'idVendor', 'idProduct', 'Manufacturer - Product'))
    print('-'*22, '-'*8,  '-'*9, '-'*30)
    # first scan
    add_usb_devices(device_dict)
    for device_info in device_dict.values():
        print(device_info)
    # next scans
    for i in range(5):  # run 5 more scans 
        new_serials = add_usb_devices(device_dict)
        if len(new_serials) > 0:
           print('** (scan %d) FOUND NEW USB DEVICES/SERIALS: %s' % (i, new_serials))
           for serial in new_serials:
               print(device_dict[serial])
        time.sleep(3)  # waiting 3 seconds before new scan
        
    str_device_dict_serial = device_dict[serial]
    listed__device_dict_serial = re.findall(r'\b\d+\b', str_device_dict_serial)
    
    #splited_str_device_dict_serial= str_device_dict_serial.split(" ")   
        
     
    print('Scans completed.')
    
    
    print("+ + + + + + + + + + + + +")
    print(str_device_dict_serial)
    print(type(str_device_dict_serial))
    print("+ + + + + + + + + + + + +")
    print(device_dict[serial])
    print(type(device_dict[serial]))
    
    print("+ + + + + + + + + + + + +")
    print(listed__device_dict_serial)
    print(type(listed__device_dict_serial))
  
  
j ton
  • 229
  • 9