(python) def return function on detecting USB connection, format error

Question:

I’m aiming to have a program can detect USB , Portable Drive or Mouse , but the function couldn’t run that I don’t see problem though.

arrange from correct function:

import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1
import re
import usb.core
import usb.util
import os
import numpy as np
import os.path
from os import path


def get_USBid(type_USB):
    try:
        busses = usb.busses()
        
        all_in_string = ' '
        for bus in busses:
            for dev in bus.devices:
                if dev:
                    xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                    if xdev._manufacturer is None:
                        xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                    if xdev._product is None:
                        xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                  
                                                
                    A = ('%8d  %9d  %s - %s' % (dev.idVendor, dev.idProduct,
                                                str(xdev._manufacturer).strip(),
                                                str(xdev._product).strip()))
          
                    all_in_string += A  + "/end/"+"n" 
                    string_splited = all_in_string.split("/end/")
       
        if type_USB == 1:
            USB_info = [s for s in string_splited if "Mass Storage Device" in s]

        if type_USB == 2:
            USB_info = [s for s in string_splited if "Portable Super Multi Drive" in s]

        if type_USB == 3:
            USB_info = [s for s in string_splited if "USB Optical Mouse" in s]
        
        USB_info_str = str(USB_info)
        y = re.findall('[0-9.]+',USB_info_str)  
        idVendor = y[0]
        idProduct = y[1]

    except Exception as e:   
        return "error in get_USBid()" 

    return USB_info


type_USB = input("Enter your USBid type: ")
result_USB = get_USBid(type_USB)
print(result_USB)

output error

Enter your USBid type: 1
error in get_USBid()

if I take off try error, there will be Tab error appear, but original function before I tried to set an input type_USB in get_USBid()

Enter your USBid type: 1
Traceback (most recent call last):
File "/home/joy/fe_dir/damm.py", line 60, in >
result_USB = get_USBid(type_USB)
File "/home/joy/fe_dir/damm.py", line 49, in get_USBid
USB_info_str = str(USB_info)
UnboundLocalError: local variable ‘USB_info’ referenced before assignment

the original correct function is below:

def list_USB_all_info():
    print ( 'idVendor  idProduct  Manufacturer - Product')
    
    busses = usb.busses()
    
    all_in_string = ' '
    for bus in busses:
        for dev in bus.devices:
            if dev:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                print ('%8d  %9d  %s - %s' % (dev.idVendor, dev.idProduct,
                                            str(xdev._manufacturer).strip(),
                                            str(xdev._product).strip()))
                                            
                A = ('%8d  %9d  %s - %s' % (dev.idVendor, dev.idProduct,
                                            str(xdev._manufacturer).strip(),
                                            str(xdev._product).strip()))
       
                all_in_string += A  + "/end/"+"n" 
                all_in_string_splited = all_in_string.split("/end/")
                         
    
    print ("= = = =")
    all_in_string_match_Mass_Storage_Device = [s for s in all_in_string_splited if "Mass Storage Device" in s]
    
    print ("+ + + +")
    all_in_string_match_Mass_Storage_Device_str = str(all_in_string_match_Mass_Storage_Device)
    y = re.findall('[0-9.]+',all_in_string_match_Mass_Storage_Device_str)  
    idVendor = y[0]
    idProduct = y[1]
    
    return all_in_string_match_Mass_Storage_Device , idVendor , idProduct

result_USB, idVendor, idProduct = list_USB_all_info()

print(result_USB)
print(idVendor)
print(idProduct)

Updated code(still have error)

import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1
import re
import usb.core
import usb.util
import os
import numpy as np
import os.path
from os import path


def get_USBid(type_USB):
    try:
        busses = usb.busses()
        
        all_in_string = ' '
        for bus in busses:
            for dev in bus.devices:
                if dev:
                    xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                    if xdev._manufacturer is None:
                        xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                    if xdev._product is None:
                        xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                  
                                                
                    A = ('%8d  %9d  %s - %s' % (dev.idVendor, dev.idProduct,
                                                str(xdev._manufacturer).strip(),
                                                str(xdev._product).strip()))
          
                    all_in_string += A  + "/end/"+"n" 
                    string_splited = all_in_string.split("/end/")
       
        USB_info = None
        if type_USB == 1:
            USB_info = [s for s in string_splited if "Mass Storage Device" in s]
        elif type_USB == 2:
            USB_info = [s for s in string_splited if "Portable Super Multi Drive" in s]
        elif type_USB == 3:
            USB_info = [s for s in string_splited if "USB Optical Mouse" in s]

        if USB_info is None:
            raise Exception('USB_info is None')
        
        USB_info_str = str(USB_info)
        y = re.findall('[0-9.]+',USB_info_str)  
        idVendor = y[0]
        idProduct = y[1]

    except Exception as e:   
        return "error in get_USBid()" 

    return USB_info


type_USB = input("Enter your USBid type: ")
result_USB = get_USBid(type_USB)
print(result_USB)

and the output

(base) joy@joy-System-Product-Name:~$ sudo python '/home/joy/fe_dir/damm.py'
Enter your USBid type: 1
error in get_USBid()
(base) joy@joy-System-Product-Name:~$ sudo python '/home/joy/fe_dir/damm.py'
Enter your USBid type: 2
error in get_USBid()
Asked By: fdu_account

||

Answers:

The issue is you are reading in the type as a string with the input but testing for equality with an int in the if statements. you should try and convert the entered value to int with int() function and pass that to your routine.

Answered By: LhasaDad

the solved one!!

import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1
import re
import usb.core
import usb.util
import os
import numpy as np
import os.path
from os import path


def get_USBid(type_USB):
    try:
        busses = usb.busses()
        
        all_in_string = ' '
        for bus in busses:
            for dev in bus.devices:
                if dev:
                    xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                    if xdev._manufacturer is None:
                        xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                    if xdev._product is None:
                        xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                  
                                                
                    A = ('%8d  %9d  %s - %s' % (dev.idVendor, dev.idProduct,
                                                str(xdev._manufacturer).strip(),
                                                str(xdev._product).strip()))
          
                    all_in_string += A  + "/end/"+"n" 
                    string_splited = all_in_string.split("/end/")
       
        USB_info = None
        type_USB_int = int(type_USB)
        if type_USB_int == 1:
            USB_info = [s for s in string_splited if "Mass Storage Device" in s]
        elif type_USB_int == 2:
            USB_info = [s for s in string_splited if "Portable Super Multi Drive" in s]
        elif type_USB_int == 3:
            USB_info = [s for s in string_splited if "USB Optical Mouse" in s]

        if USB_info is None:
            raise Exception('USB_info is None')
        
        USB_info_str = str(USB_info)
        y = re.findall('[0-9.]+',USB_info_str)  
        idVendor = y[0]
        idProduct = y[1]

    except Exception as e:   
        return "error in get_USBid()" 

    return USB_info


type_USB = input("Enter your USBid type: ")
result_USB = get_USBid(type_USB)
print(result_USB)

Answered By: fdu_account
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.