usbutils - various patches to the lsusb.py script
Hi,
I accidentally ended up hacking on the lsusb.py script and now have an assorted collection of patches:
- Output (controllers, hubs, etc.) sorted numerically.
- Color enabled by default when on a tty.
- Added --long-options.
- Replaced hand-rolled binary search with ordinary dict lookups; lost the -w (--warn-if-unsorted) option in the process.
- Cosmetic changes to make it look more like Python and less like C.
- Some changes to the output formatting that I liked to have in my own local version.
PATCH 1/34 lsusb.py: sort devices and interfaces numerically
--- lsusb.py.in | 3 +++ 1 file changed, 3 insertions(+)
lsusb.py.in +3 -0
@@ -477,6 +477,9 @@ class UsbDevice: usbdev.read(dirent) usbdev.readchildren() self.children.append(usbdev) + usbsortkey = lambda obj: [int(x) for x in re.split(r"[-:.]", obj.fname)] + self.interfaces.sort(key=usbsortkey) + self.children.sort(key=usbsortkey) def __str__(self): #str = " " * self.level + self.fname
Signature · 1 line
2.21.0
PATCH 2/34 lsusb.py: sort toplevel entries
In reply to Mantas Mikulėnas--- lsusb.py.in | 4 ++++ 1 file changed, 4 insertions(+)
lsusb.py.in +4 -0
@@ -580,6 +580,7 @@ def usage(): def read_usb(): "Read toplevel USB entries and print" + root_hubs = [] for dirent in os.listdir(prefix): #print(dirent,) if not dirent[0:3] == "usb":
@@ -587,6 +588,9 @@ def read_usb(): usbdev = UsbDevice(None, 0) usbdev.read(dirent) usbdev.readchildren() + root_hubs.append(usbdev) + root_hubs.sort(key=lambda x: int(x.fname[3:])) + for usbdev in root_hubs: os.write(sys.stdout.fileno(), str.encode(usbdev.__str__())) #print(usbdev.__str__())
Signature · 1 line
2.21.0
PATCH 3/34 lsusb.py: improve usage text
In reply to Mantas Mikulėnas--- lsusb.py.in | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-)
lsusb.py.in +14 -12
@@ -565,18 +565,20 @@ def fix_usbclass(): def usage(): "Displays usage information" print("Usage: lsusb.py [options]") + print() print("Options:") - print(" -h display this help") - print(" -i display interface information") - print(" -I display interface information, even for hubs") - print(" -u suppress empty hubs") - print(" -U suppress all hubs") - print(" -c use colors") - print(" -e display endpoint info") - print(" -w display warning if usb.ids is not sorted correctly") - print(" -f FILE override filename for /usr/share/usb.ids") + # "|-------|-------|-------|-------|-------" + print(" -h display this help") + print(" -i display interface information") + print(" -I display interface information, even for hubs") + print(" -u suppress empty hubs") + print(" -U suppress all hubs") + print(" -c use colors") + print(" -e display endpoint info") + print(" -w display warning if usb.ids is not sorted correctly") + print(" -f FILE override filename for /usr/share/usb.ids") + print() print("Use lsusb.py -ciu to get a nice overview of your USB devices.") - return 2 def read_usb(): "Read toplevel USB entries and print"
@@ -602,7 +604,7 @@ def main(argv): (optlist, args) = getopt.gnu_getopt(argv[1:], "hiIuUwcef:", ("help",)) except getopt.GetoptError as exc: print("Error:", exc) - sys.exit(usage()) + sys.exit(2) for opt in optlist: if opt[0] == "-h" or opt[0] == "--help": usage()
@@ -636,7 +638,7 @@ def main(argv): continue if len(args) > 0: print("Error: excess args %s ..." % args[0]) - sys.exit(usage()) + sys.exit(2) if usbids[0]: try:
Signature · 1 line
2.21.0
PATCH 4/34 lsusb.py: replace fake deepcopy()
In reply to Mantas MikulėnasIt doesn't actually do a deep copy, and Python already has ways of doing a shallow copy (list(foo) and [*foo] for arbitrary iterables; foo[:] for indexable lists).
--- lsusb.py.in | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-)
lsusb.py.in +3 -10
@@ -518,13 +518,6 @@ class UsbDevice: str += child.__str__() return str -def deepcopy(lst): - "Returns a deep copy from the list lst" - copy = [] - for item in lst: - copy.append(item) - return copy - def display_diff(lst1, lst2, fmtstr, args): "Compare lists (same length!) and display differences" for idx in range(0, len(lst1)):
@@ -534,7 +527,7 @@ def display_diff(lst1, lst2, fmtstr, args): def fix_usbvend(): "Sort USB vendor list and (optionally) display diffs" if warnsort: - oldusbvend = deepcopy(usbvendors) + oldusbvend = usbvendors[:] usbvendors.sort() if warnsort: display_diff(usbvendors, oldusbvend,
@@ -544,7 +537,7 @@ def fix_usbvend(): def fix_usbprod(): "Sort USB products list" if warnsort: - oldusbprod = deepcopy(usbproducts) + oldusbprod = usbproducts[:] usbproducts.sort() if warnsort: display_diff(usbproducts, oldusbprod,
@@ -554,7 +547,7 @@ def fix_usbprod(): def fix_usbclass(): "Sort USB class list" if warnsort: - oldusbcls = deepcopy(usbclasses) + oldusbcls = usbclasses[:] usbclasses.sort() if warnsort: display_diff(usbclasses, oldusbcls,
Signature · 1 line
2.21.0
PATCH 5/34 lsusb.py: remove -w (warn if usb.ids not sorted) option
In reply to Mantas Mikulėnas--- lsusb.py.in | 45 ++------------------------------------------- 1 file changed, 2 insertions(+), 43 deletions(-)
lsusb.py.in +2 -43
@@ -19,7 +19,6 @@ showint = False showhubint = False noemptyhub = False nohub = False -warnsort = False showeps = False prefix = "/sys/bus/usb/devices/"
@@ -518,42 +517,6 @@ class UsbDevice: str += child.__str__() return str -def display_diff(lst1, lst2, fmtstr, args): - "Compare lists (same length!) and display differences" - for idx in range(0, len(lst1)): - if lst1[idx] != lst2[idx]: - print("Warning: " + fmtstr % args(lst2[idx])) - -def fix_usbvend(): - "Sort USB vendor list and (optionally) display diffs" - if warnsort: - oldusbvend = usbvendors[:] - usbvendors.sort() - if warnsort: - display_diff(usbvendors, oldusbvend, - "Unsorted Vendor ID %04x", - lambda x: (x.vid,)) - -def fix_usbprod(): - "Sort USB products list" - if warnsort: - oldusbprod = usbproducts[:] - usbproducts.sort() - if warnsort: - display_diff(usbproducts, oldusbprod, - "Unsorted Vendor:Product ID %04x:%04x", - lambda x: (x.vid, x.pid)) - -def fix_usbclass(): - "Sort USB class list" - if warnsort: - oldusbcls = usbclasses[:] - usbclasses.sort() - if warnsort: - display_diff(usbclasses, oldusbcls, - "Unsorted USB class %02x:%02x:%02x", - lambda x: (x.pclass, x.subclass, x.proto)) - def usage(): "Displays usage information"
@@ -568,7 +531,6 @@ def usage(): print(" -U suppress all hubs") print(" -c use colors") print(" -e display endpoint info") - print(" -w display warning if usb.ids is not sorted correctly") print(" -f FILE override filename for /usr/share/usb.ids") print() print("Use lsusb.py -ciu to get a nice overview of your USB devices.")
@@ -592,7 +554,7 @@ def read_usb(): def main(argv): "main entry point" global showint, showhubint, noemptyhub, nohub - global warnsort, cols, usbids, showeps + global cols, usbids, showeps try: (optlist, args) = getopt.gnu_getopt(argv[1:], "hiIuUwcef:", ("help",)) except getopt.GetoptError as exc:
@@ -620,7 +582,7 @@ def main(argv): cols = (norm, bold, red, green, amber, blue) continue if opt[0] == "-w": - warnsort = True + print("Warning: option -w is no longer supported", file=sys.stderr) continue if opt[0] == "-f": #usbids = (opt[1], *usbids)
@@ -636,9 +598,6 @@ def main(argv): if usbids[0]: try: parse_usb_ids() - fix_usbvend() - fix_usbprod() - fix_usbclass() except: print(" WARNING: Failure to read usb.ids", file=sys.stderr) #print(sys.exc_info(), file=sys.stderr)
Signature · 1 line
2.21.0
PATCH 6/34 lsusb.py: ensure all error messages are written to stderr
In reply to Mantas Mikulėnas--- lsusb.py.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
lsusb.py.in +2 -2
@@ -558,7 +558,7 @@ def main(argv): try: (optlist, args) = getopt.gnu_getopt(argv[1:], "hiIuUwcef:", ("help",)) except getopt.GetoptError as exc: - print("Error:", exc) + print("Error:", exc, file=sys.stderr) sys.exit(2) for opt in optlist: if opt[0] == "-h" or opt[0] == "--help":
@@ -592,7 +592,7 @@ def main(argv): showeps = True continue if len(args) > 0: - print("Error: excess args %s ..." % args[0]) + print("Error: excess args %s ..." % args[0], file=sys.stderr) sys.exit(2) if usbids[0]:
Signature · 1 line
2.21.0
PATCH 7/34 lsusb.py: support long options
In reply to Mantas Mikulėnas--- lsusb.py.in | 48 ++++++++++++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 18 deletions(-)
lsusb.py.in +30 -18
@@ -523,15 +523,15 @@ def usage(): print("Usage: lsusb.py [options]") print() print("Options:") - # "|-------|-------|-------|-------|-------" - print(" -h display this help") - print(" -i display interface information") - print(" -I display interface information, even for hubs") - print(" -u suppress empty hubs") - print(" -U suppress all hubs") - print(" -c use colors") - print(" -e display endpoint info") - print(" -f FILE override filename for /usr/share/usb.ids") + print(" -h, --help display this help") + print(" -i, --interfaces display interface information") + print(" -I, --hub-interfaces display interface information, even for hubs") + print(" -u, --hide-empty-hubs suppress empty hubs") + print(" -U, --hide-hubs suppress all hubs") + print(" -c, --color use colors") + print(" -e, --endpoints display endpoint info") + print(" -f FILE, --usbids-path FILE") + print(" override filename for /usr/share/usb.ids") print() print("Use lsusb.py -ciu to get a nice overview of your USB devices.")
@@ -555,40 +555,52 @@ def main(argv): "main entry point" global showint, showhubint, noemptyhub, nohub global cols, usbids, showeps + + long_options = [ + "help", + "interfaces", + "hub-interfaces", + "hide-empty-hubs", + "hide-hubs", + "color", + "usbids-path=", + "endpoints", + ] + try: - (optlist, args) = getopt.gnu_getopt(argv[1:], "hiIuUwcef:", ("help",)) + (optlist, args) = getopt.gnu_getopt(argv[1:], "hiIuUwcef:", long_options) except getopt.GetoptError as exc: print("Error:", exc, file=sys.stderr) sys.exit(2) for opt in optlist: - if opt[0] == "-h" or opt[0] == "--help": + if opt[0] in {"-h", "--help"}: usage() sys.exit(0) - if opt[0] == "-i": + if opt[0] in {"-i", "--interfaces"}: showint = True continue - if opt[0] == "-I": + if opt[0] in {"-I", "--hub-interfaces"}: showint = True showhubint = True continue - if opt[0] == "-u": + if opt[0] in {"-u", "--hide-empty-hubs"}: noemptyhub = True continue - if opt[0] == "-U": + if opt[0] in {"-U", "--hide-hubs"}: noemptyhub = True nohub = True continue - if opt[0] == "-c": + if opt[0] in {"-c", "--color"}: cols = (norm, bold, red, green, amber, blue) continue if opt[0] == "-w": print("Warning: option -w is no longer supported", file=sys.stderr) continue - if opt[0] == "-f": + if opt[0] in {"-f", "--usbids-path"}: #usbids = (opt[1], *usbids) usbids = (opt[1],) continue - if opt[0] == "-e": + if opt[0] in {"-e", "--endpoints"}: showeps = True continue if len(args) > 0:
Signature · 1 line
2.21.0
PATCH 8/34 lsusb.py: do not entirely hide usb.ids exceptions
In reply to Mantas Mikulėnas--- lsusb.py.in | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
lsusb.py.in +2 -3
@@ -610,9 +610,8 @@ def main(argv): if usbids[0]: try: parse_usb_ids() - except: - print(" WARNING: Failure to read usb.ids", file=sys.stderr) - #print(sys.exc_info(), file=sys.stderr) + except IOError as e: + print("Warning: Failure to read usb.ids:", e, file=sys.stderr) read_usb() # Entry point
Signature · 1 line
2.21.0
PATCH 9/34 lsusb.py: use regular print() instead of hand-rolling the same thing
In reply to Mantas MikulėnasEven sys.stdout.write(str(usbdev)) would have been better.
--- lsusb.py.in | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
lsusb.py.in +1 -2
@@ -548,8 +548,7 @@ def read_usb(): root_hubs.append(usbdev) root_hubs.sort(key=lambda x: int(x.fname[3:])) for usbdev in root_hubs: - os.write(sys.stdout.fileno(), str.encode(usbdev.__str__())) - #print(usbdev.__str__()) + print(usbdev, end="") def main(argv): "main entry point"
Signature · 1 line
2.21.0
PATCH 10/34 lsusb.py: avoid shadowing Python's built-in 'str'
In reply to Mantas Mikulėnas--- lsusb.py.in | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-)
lsusb.py.in +12 -12
@@ -45,11 +45,11 @@ def readlink(path, name): class UsbClass: "Container for USB Class/Subclass/Protocol" - def __init__(self, cl, sc, pr, str = ""): + def __init__(self, cl, sc, pr, strg = ""): self.pclass = cl self.subclass = sc self.proto = pr - self.desc = str + self.desc = strg def __repr__(self): return self.desc def __lt__(self, oth):
@@ -481,13 +481,13 @@ class UsbDevice: self.children.sort(key=usbsortkey) def __str__(self): - #str = " " * self.level + self.fname + #strg = " " * self.level + self.fname if self.iclass == 9: col = cols[2] if noemptyhub and len(self.children) == 0: return "" if nohub: - str = "" + strg = "" else: col = cols[1] if not nohub or self.iclass != 9:
@@ -495,27 +495,27 @@ class UsbDevice: plural = " " else: plural = "s" - str = "%-16s %s%04x:%04x%s %02x %s%6sMbit/s %5s %iIF%s (%s%s%s)" % \ + strg = "%-16s %s%04x:%04x%s %02x %s%6sMbit/s %5s %iIF%s (%s%s%s)" % \ (" " * self.level + self.fname, cols[1], self.vid, self.pid, cols[0], self.iclass, self.usbver, self.speed, self.maxpower, self.nointerfaces, plural, col, self.name, cols[0]) #if self.driver != "usb": - # str += " %s" % self.driver + # strg += " %s" % self.driver if self.iclass == 9 and not showhubint: - str += " %shub%s\n" % (cols[2], cols[0]) + strg += " %shub%s\n" % (cols[2], cols[0]) else: - str += "\n" + strg += "\n" if showeps: ep = UsbEndpoint(self, self.level+len(self.fname)) ep.read("ep_00") - str += ep.__str__() + strg += ep.__str__() if showint: for iface in self.interfaces: - str += iface.__str__() + strg += iface.__str__() for child in self.children: - str += child.__str__() - return str + strg += child.__str__() + return strg def usage():
Signature · 1 line
2.21.0
PATCH 11/34 lsusb.py: replace usb.ids binary search with dict lookup
In reply to Mantas MikulėnasThere is no significant gain in reinventing the wheel here.
--- lsusb.py.in | 53 +++++++++++++++++++++++------------------------------ 1 file changed, 23 insertions(+), 30 deletions(-)
lsusb.py.in +23 -30
@@ -84,9 +84,9 @@ class UsbProduct: def __eq__(self, oth): return (self.vid, self.pid) == (oth.vid, oth.pid) -usbvendors = [] -usbproducts = [] -usbclasses = [] +usbvendors = {} +usbproducts = {} +usbclasses = {} def ishexdigit(str): "return True if all digits are valid hex digits"
@@ -125,7 +125,7 @@ def parse_usb_ids(): if ishexdigit(ln[0:4]): mode = modes.Vendor vid = int(ln[:4], 16) - usbvendors.append(UsbVendor(vid, ln[6:])) + usbvendors[vid] = UsbVendor(vid, ln[6:]) continue if ln[0] == '\t' and ishexdigit(ln[1:3]): # usb.ids has a device id of 01xy, sigh
@@ -135,7 +135,7 @@ def parse_usb_ids(): did = int(ln[1:5], 16) # USB devices if mode == modes.Vendor: - usbproducts.append(UsbProduct(vid, did, ln[7:])) + usbproducts[vid, did] = UsbProduct(vid, did, ln[7:]) continue elif mode == modes.Class: nm = ln[5:]
@@ -143,17 +143,17 @@ def parse_usb_ids(): strg = cstrg + ":" + nm else: strg = cstrg + ":" - usbclasses.append(UsbClass(vid, did, -1, strg)) + usbclasses[vid, did, -1] = UsbClass(vid, did, -1, strg) continue if ln[0] == 'C': mode = modes.Class cid = int(ln[2:4], 16) cstrg = ln[6:] - usbclasses.append(UsbClass(cid, -1, -1, cstrg)) + usbclasses[cid, -1, -1] = UsbClass(cid, -1, -1, cstrg) continue if mode == modes.Class and ln[0] == '\t' and ln[1] == '\t' and ishexdigit(ln[2:4]): prid = int(ln[2:4], 16) - usbclasses.append(UsbClass(cid, did, prid, strg + ":" + ln[6:])) + usbclasses[cid, did, prid] = UsbClass(cid, did, prid, strg + ":" + ln[6:]) continue mode = modes.Misc
@@ -179,18 +179,14 @@ def bin_search(first, last, item, list): def find_usb_prod(vid, pid): "Return device name from USB Vendor:Product list" strg = "" - dev = UsbVendor(vid, "") - lnvend = len(usbvendors) - ix = bin_search(0, lnvend, dev, usbvendors) - if ix != -1: - strg = usbvendors[ix].__repr__() + vendor = usbvendors.get(vid) + if vendor: + strg = vendor.__repr__() else: return "" - dev = UsbProduct(vid, pid, "") - lnprod = len(usbproducts) - ix = bin_search(0, lnprod, dev, usbproducts) - if ix != -1: - return strg + " " + usbproducts[ix].__repr__() + product = usbproducts.get((vid, pid)) + if product: + return strg + " " + product.__repr__() return strg def find_usb_class(cid, sid, pid):
@@ -198,18 +194,15 @@ def find_usb_class(cid, sid, pid): if cid == 0xff and sid == 0xff and pid == 0xff: return "Vendor Specific" lnlst = len(usbclasses) - dev = UsbClass(cid, sid, pid, "") - ix = bin_search(0, lnlst, dev, usbclasses) - if ix != -1: - return usbclasses[ix].__repr__() - dev = UsbClass(cid, sid, -1, "") - ix = bin_search(0, lnlst, dev, usbclasses) - if ix != -1: - return usbclasses[ix].__repr__() - dev = UsbClass(cid, -1, -1, "") - ix = bin_search(0, lnlst, dev, usbclasses) - if ix != -1: - return usbclasses[ix].__repr__() + cls = usbclasses.get((cid, sid, pid)) + if cls: + return cls.__repr__() + cls = usbclasses.get((cid, sid, -1)) + if cls: + return cls.__repr__() + cls = usbclasses.get((cid, -1, -1)) + if cls: + return cls.__repr__() return ""
Signature · 1 line
2.21.0
PATCH 12/34 lsusb.py: remove now-unused bin_search()
In reply to Mantas Mikulėnas--- lsusb.py.in | 19 ------------------- 1 file changed, 19 deletions(-)
lsusb.py.in +0 -19
@@ -157,25 +157,6 @@ def parse_usb_ids(): continue mode = modes.Misc -def bin_search(first, last, item, list): - "binary search on list, returns -1 on fail, match idx otherwise, recursive" - #print("bin_search(%i,%i)" % (first, last)) - if first == last: - return -1 - if first == last-1: - if item == list[first]: - return first - else: - return -1 - mid = (first+last) // 2 - if item == list[mid]: - return mid - elif item < list[mid]: - return bin_search(first, mid, item, list) - else: - return bin_search(mid, last, item, list) - - def find_usb_prod(vid, pid): "Return device name from USB Vendor:Product list" strg = ""
Signature · 1 line
2.21.0
PATCH 13/34 lsusb.py: avoid manual calls to __foo__()
In reply to Mantas Mikulėnas--- lsusb.py.in | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)
lsusb.py.in +9 -9
@@ -162,12 +162,12 @@ def find_usb_prod(vid, pid): strg = "" vendor = usbvendors.get(vid) if vendor: - strg = vendor.__repr__() + strg = repr(vendor) else: return "" product = usbproducts.get((vid, pid)) if product: - return strg + " " + product.__repr__() + return strg + " " + repr(product) return strg def find_usb_class(cid, sid, pid):
@@ -177,13 +177,13 @@ def find_usb_class(cid, sid, pid): lnlst = len(usbclasses) cls = usbclasses.get((cid, sid, pid)) if cls: - return cls.__repr__() + return repr(cls) cls = usbclasses.get((cid, sid, -1)) if cls: - return cls.__repr__() + return repr(cls) cls = usbclasses.get((cid, -1, -1)) if cls: - return cls.__repr__() + return repr(cls) return ""
@@ -355,7 +355,7 @@ class UsbInterface: cols[4], self.devname, cols[0]) if showeps and self.eps: for ep in self.eps: - strg += ep.__str__() + strg += str(ep) return strg class UsbDevice:
@@ -483,12 +483,12 @@ class UsbDevice: if showeps: ep = UsbEndpoint(self, self.level+len(self.fname)) ep.read("ep_00") - strg += ep.__str__() + strg += str(ep) if showint: for iface in self.interfaces: - strg += iface.__str__() + strg += str(iface) for child in self.children: - strg += child.__str__() + strg += str(child) return strg
Signature · 1 line
2.21.0
PATCH 14/34 lsusb.py: replace __repr__() for USB IDs with __str__()
In reply to Mantas MikulėnasThis is more suitable for a method that returns human-oriented strings.
--- lsusb.py.in | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
lsusb.py.in +8 -8
@@ -50,7 +50,7 @@ class UsbClass: self.subclass = sc self.proto = pr self.desc = strg - def __repr__(self): + def __str__(self): return self.desc def __lt__(self, oth): return (self.pclass, self.subclass, self.proto) < \
@@ -64,7 +64,7 @@ class UsbVendor: def __init__(self, vid, vname = ""): self.vid = vid self.vname = vname - def __repr__(self): + def __str__(self): return self.vname def __lt__(self, oth): return self.vid < oth.vid
@@ -77,7 +77,7 @@ class UsbProduct: self.vid = vid self.pid = pid self.pname = pname - def __repr__(self): + def __str__(self): return self.pname def __lt__(self, oth): return (self.vid, self.pid) < (oth.vid, oth.pid)
@@ -162,12 +162,12 @@ def find_usb_prod(vid, pid): strg = "" vendor = usbvendors.get(vid) if vendor: - strg = repr(vendor) + strg = str(vendor) else: return "" product = usbproducts.get((vid, pid)) if product: - return strg + " " + repr(product) + return strg + " " + str(product) return strg def find_usb_class(cid, sid, pid):
@@ -177,13 +177,13 @@ def find_usb_class(cid, sid, pid): lnlst = len(usbclasses) cls = usbclasses.get((cid, sid, pid)) if cls: - return repr(cls) + return str(cls) cls = usbclasses.get((cid, sid, -1)) if cls: - return repr(cls) + return str(cls) cls = usbclasses.get((cid, -1, -1)) if cls: - return repr(cls) + return str(cls) return ""
Signature · 1 line
2.21.0
PATCH 15/34 lsusb.py: insert class FF:FF:FF into usbclasses to avoid special casing
In reply to Mantas Mikulėnas--- lsusb.py.in | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
lsusb.py.in +1 -2
@@ -156,6 +156,7 @@ def parse_usb_ids(): usbclasses[cid, did, prid] = UsbClass(cid, did, prid, strg + ":" + ln[6:]) continue mode = modes.Misc + usbclasses[0xFF, 0xFF, 0xFF] = UsbClass(0xFF, 0xFF, 0xFF, "Vendor Specific") def find_usb_prod(vid, pid): "Return device name from USB Vendor:Product list"
@@ -172,8 +173,6 @@ def find_usb_prod(vid, pid): def find_usb_class(cid, sid, pid): "Return USB protocol from usbclasses list" - if cid == 0xff and sid == 0xff and pid == 0xff: - return "Vendor Specific" lnlst = len(usbclasses) cls = usbclasses.get((cid, sid, pid)) if cls:
Signature · 1 line
2.21.0
PATCH 16/34 lsusb.py: entirely remove Usb* classes
In reply to Mantas MikulėnasTheir main purpose in life was to be sortable, which we no longer do.
--- lsusb.py.in | 53 ++++++----------------------------------------------- 1 file changed, 6 insertions(+), 47 deletions(-)
lsusb.py.in +6 -47
@@ -43,47 +43,6 @@ def readlink(path, name): "Read symlink and return basename" return os.path.basename(os.readlink(prefix + path + "/" + name)); -class UsbClass: - "Container for USB Class/Subclass/Protocol" - def __init__(self, cl, sc, pr, strg = ""): - self.pclass = cl - self.subclass = sc - self.proto = pr - self.desc = strg - def __str__(self): - return self.desc - def __lt__(self, oth): - return (self.pclass, self.subclass, self.proto) < \ - (oth.pclass, oth.subclass, oth.proto) - def __eq__(self, oth): - return (self.pclass, self.subclass, self.proto) == \ - (oth.pclass, oth.subclass, oth.proto) - -class UsbVendor: - "Container for USB Vendors" - def __init__(self, vid, vname = ""): - self.vid = vid - self.vname = vname - def __str__(self): - return self.vname - def __lt__(self, oth): - return self.vid < oth.vid - def __eq__(self, oth): - return self.vid == oth.vid - -class UsbProduct: - "Container for USB VID:PID devices" - def __init__(self, vid, pid, pname = ""): - self.vid = vid - self.pid = pid - self.pname = pname - def __str__(self): - return self.pname - def __lt__(self, oth): - return (self.vid, self.pid) < (oth.vid, oth.pid) - def __eq__(self, oth): - return (self.vid, self.pid) == (oth.vid, oth.pid) - usbvendors = {} usbproducts = {} usbclasses = {}
@@ -125,7 +84,7 @@ def parse_usb_ids(): if ishexdigit(ln[0:4]): mode = modes.Vendor vid = int(ln[:4], 16) - usbvendors[vid] = UsbVendor(vid, ln[6:]) + usbvendors[vid] = ln[6:] continue if ln[0] == '\t' and ishexdigit(ln[1:3]): # usb.ids has a device id of 01xy, sigh
@@ -135,7 +94,7 @@ def parse_usb_ids(): did = int(ln[1:5], 16) # USB devices if mode == modes.Vendor: - usbproducts[vid, did] = UsbProduct(vid, did, ln[7:]) + usbproducts[vid, did] = ln[7:] continue elif mode == modes.Class: nm = ln[5:]
@@ -143,20 +102,20 @@ def parse_usb_ids(): strg = cstrg + ":" + nm else: strg = cstrg + ":" - usbclasses[vid, did, -1] = UsbClass(vid, did, -1, strg) + usbclasses[vid, did, -1] = strg continue if ln[0] == 'C': mode = modes.Class cid = int(ln[2:4], 16) cstrg = ln[6:] - usbclasses[cid, -1, -1] = UsbClass(cid, -1, -1, cstrg) + usbclasses[cid, -1, -1] = cstrg continue if mode == modes.Class and ln[0] == '\t' and ln[1] == '\t' and ishexdigit(ln[2:4]): prid = int(ln[2:4], 16) - usbclasses[cid, did, prid] = UsbClass(cid, did, prid, strg + ":" + ln[6:]) + usbclasses[cid, did, prid] = ln[6:] continue mode = modes.Misc - usbclasses[0xFF, 0xFF, 0xFF] = UsbClass(0xFF, 0xFF, 0xFF, "Vendor Specific") + usbclasses[0xFF, 0xFF, 0xFF] = "Vendor Specific" def find_usb_prod(vid, pid): "Return device name from USB Vendor:Product list"
Signature · 1 line
2.21.0
PATCH 17/34 lsusb.py: cosmetic - replace tuples-as-"immutable lists" with regular lists
In reply to Mantas Mikulėnas--- lsusb.py.in | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-)
lsusb.py.in +22 -17
@@ -22,7 +22,12 @@ nohub = False showeps = False prefix = "/sys/bus/usb/devices/" -usbids = ("@usbids@", "/usr/share/usb.ids", "/usr/share/libosinfo/usb.ids", "/usr/share/kcmusb/usb.ids", ) +usbids = [ + "@usbids@", + "/usr/share/usb.ids", + "/usr/share/libosinfo/usb.ids", + "/usr/share/kcmusb/usb.ids", +] esc = chr(27) norm = esc + "[0;0m"
@@ -145,20 +150,21 @@ def find_usb_class(cid, sid, pid): return "" -devlst = ( 'host', # usb-storage - 'video4linux/video', # uvcvideo et al. - 'sound/card', # snd-usb-audio - 'net/', # cdc_ether, ... - 'input/input', # usbhid - 'usb:hiddev', # usb hid - 'bluetooth/hci', # btusb - 'ttyUSB', # btusb - 'tty/', # cdc_acm - 'usb:lp', # usblp - #'usb/lp', # usblp - 'usb/', # hiddev, usblp - #'usbhid', # hidraw - ) +devlst = [ + 'host', # usb-storage + 'video4linux/video', # uvcvideo et al. + 'sound/card', # snd-usb-audio + 'net/', # cdc_ether, ... + 'input/input', # usbhid + 'usb:hiddev', # usb hid + 'bluetooth/hci', # btusb + 'ttyUSB', # btusb + 'tty/', # cdc_acm + 'usb:lp', # usblp + #'usb/lp', # usblp + 'usb/', # hiddev, usblp + #'usbhid', # hidraw +] def find_storage(hostno): "Return SCSI block dev names for host"
@@ -528,8 +534,7 @@ def main(argv): print("Warning: option -w is no longer supported", file=sys.stderr) continue if opt[0] in {"-f", "--usbids-path"}: - #usbids = (opt[1], *usbids) - usbids = (opt[1],) + usbids = [opt[1]] continue if opt[0] in {"-e", "--endpoints"}: showeps = True
Signature · 1 line
2.21.0
PATCH 18/34 lsusb.py: use 'elif' where suitable
In reply to Mantas Mikulėnas--- lsusb.py.in | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-)
lsusb.py.in +12 -17
@@ -12,7 +12,10 @@ # Py2 compat from __future__ import print_function -import os, sys, re, getopt +import getopt +import os +import re +import sys # Global options showint = False
@@ -513,32 +516,24 @@ def main(argv): if opt[0] in {"-h", "--help"}: usage() sys.exit(0) - if opt[0] in {"-i", "--interfaces"}: + elif opt[0] in {"-i", "--interfaces"}: showint = True - continue - if opt[0] in {"-I", "--hub-interfaces"}: + elif opt[0] in {"-I", "--hub-interfaces"}: showint = True showhubint = True - continue - if opt[0] in {"-u", "--hide-empty-hubs"}: + elif opt[0] in {"-u", "--hide-empty-hubs"}: noemptyhub = True - continue - if opt[0] in {"-U", "--hide-hubs"}: + elif opt[0] in {"-U", "--hide-hubs"}: noemptyhub = True nohub = True - continue - if opt[0] in {"-c", "--color"}: + elif opt[0] in {"-c", "--color"}: cols = (norm, bold, red, green, amber, blue) - continue - if opt[0] == "-w": + elif opt[0] == "-w": print("Warning: option -w is no longer supported", file=sys.stderr) - continue - if opt[0] in {"-f", "--usbids-path"}: + elif opt[0] in {"-f", "--usbids-path"}: usbids = [opt[1]] - continue - if opt[0] in {"-e", "--endpoints"}: + elif opt[0] in {"-e", "--endpoints"}: showeps = True - continue if len(args) > 0: print("Error: excess args %s ..." % args[0], file=sys.stderr) sys.exit(2)
Signature · 1 line
2.21.0
PATCH 19/34 lsusb.py: remove dead code
In reply to Mantas Mikulėnas--- lsusb.py.in | 11 ----------- 1 file changed, 11 deletions(-)
lsusb.py.in +0 -11
@@ -200,18 +200,15 @@ def add_drv(path, drvnm): def find_dev(driver, usbname): "Return pseudo devname that's driven by driver" res = "" - #print("find_dev(%s, %s)" % (driver, usbname)) for nm in devlst: dirnm = prefix + usbname prep = "" - #print(nm) idx = nm.find('/') if idx != -1: prep = nm[:idx+1] dirnm += "/" + nm[:idx] nm = nm[idx+1:] ln = len(nm) - #print(" search %s for %s" % (dirnm, nm)) try: for ent in os.listdir(dirnm): if ent[:ln] == nm:
@@ -359,7 +356,6 @@ class UsbDevice: try: self.name = readattr(fname, "manufacturer") + " " \ + readattr(fname, "product") - #self.name += " " + readattr(fname, "serial") if self.name[:5] == "Linux": rx = re.compile(r"Linux [^ ]* (.hci_hcd) .HCI Host Controller") mch = rx.match(self.name)
@@ -390,8 +386,6 @@ class UsbDevice: try: self.nointerfaces = int(readattr(fname, "bNumInterfaces")) except: - #print("ERROR: %s/bNumInterfaces = %s" % (fname, - # readattr(fname, "bNumInterfaces"))) self.nointerfaces = 0 try: self.driver = readlink(fname, "driver")
@@ -407,7 +401,6 @@ class UsbDevice: for dirent in os.listdir(prefix + self.fname): if not dirent[0:1].isdigit(): continue - #print(dirent) if os.access(prefix + dirent + "/bInterfaceClass", os.R_OK): iface = UsbInterface(self, self.level+1) iface.read(dirent)
@@ -422,7 +415,6 @@ class UsbDevice: self.children.sort(key=usbsortkey) def __str__(self): - #strg = " " * self.level + self.fname if self.iclass == 9: col = cols[2] if noemptyhub and len(self.children) == 0:
@@ -441,8 +433,6 @@ class UsbDevice: cols[1], self.vid, self.pid, cols[0], self.iclass, self.usbver, self.speed, self.maxpower, self.nointerfaces, plural, col, self.name, cols[0]) - #if self.driver != "usb": - # strg += " %s" % self.driver if self.iclass == 9 and not showhubint: strg += " %shub%s\n" % (cols[2], cols[0]) else:
@@ -480,7 +470,6 @@ def read_usb(): "Read toplevel USB entries and print" root_hubs = [] for dirent in os.listdir(prefix): - #print(dirent,) if not dirent[0:3] == "usb": continue usbdev = UsbDevice(None, 0)
Signature · 1 line
2.21.0
PATCH 20/34 lsusb.py: move unrelated code out of try..except
In reply to Mantas Mikulėnas--- lsusb.py.in | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-)
lsusb.py.in +4 -6
@@ -356,14 +356,12 @@ class UsbDevice: try: self.name = readattr(fname, "manufacturer") + " " \ + readattr(fname, "product") - if self.name[:5] == "Linux": - rx = re.compile(r"Linux [^ ]* (.hci_hcd) .HCI Host Controller") - mch = rx.match(self.name) - if mch: - self.name = mch.group(1) - except: pass + if self.name and self.name[:5] == "Linux": + mch = re.match(r"Linux [^ ]* (.hci_hcd) .HCI Host Controller", self.name) + if mch: + self.name = mch.group(1) if not self.name: self.name = find_usb_prod(self.vid, self.pid) # Some USB Card readers have a better name then Generic ...
Signature · 1 line
2.21.0
PATCH 21/34 lsusb.py: allow - as well as _ when matching hci module names
In reply to Mantas Mikulėnas--- lsusb.py.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
lsusb.py.in +1 -1
@@ -359,7 +359,7 @@ class UsbDevice: except: pass if self.name and self.name[:5] == "Linux": - mch = re.match(r"Linux [^ ]* (.hci_hcd) .HCI Host Controller", self.name) + mch = re.match(r"Linux [^ ]* (.hci[_-]hcd) .HCI Host Controller", self.name) if mch: self.name = mch.group(1) if not self.name:
Signature · 1 line
2.21.0
PATCH 22/34 lsusb.py: use a constant for the magic class number 9
In reply to Mantas Mikulėnas--- lsusb.py.in | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
lsusb.py.in +5 -3
@@ -17,6 +17,8 @@ import os import re import sys +HUB_ICLASS = 0x09 + # Global options showint = False showhubint = False
@@ -413,7 +415,7 @@ class UsbDevice: self.children.sort(key=usbsortkey) def __str__(self): - if self.iclass == 9: + if self.iclass == HUB_ICLASS: col = cols[2] if noemptyhub and len(self.children) == 0: return ""
@@ -421,7 +423,7 @@ class UsbDevice: strg = "" else: col = cols[1] - if not nohub or self.iclass != 9: + if not nohub or self.iclass != HUB_ICLASS: if self.nointerfaces == 1: plural = " " else:
@@ -431,7 +433,7 @@ class UsbDevice: cols[1], self.vid, self.pid, cols[0], self.iclass, self.usbver, self.speed, self.maxpower, self.nointerfaces, plural, col, self.name, cols[0]) - if self.iclass == 9 and not showhubint: + if self.iclass == HUB_ICLASS and not showhubint: strg += " %shub%s\n" % (cols[2], cols[0]) else: strg += "\n"
Signature · 1 line
2.21.0
PATCH 23/34 lsusb.py: Usb* classes: call read() automatically from constructor
In reply to Mantas Mikulėnas--- lsusb.py.in | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-)
lsusb.py.in +21 -20
@@ -238,16 +238,18 @@ def find_dev(driver, usbname): class UsbEndpoint: "Container for USB endpoint info" - def __init__(self, parent = None, indent = 18): + def __init__(self, parent, fname, indent=18): self.parent = parent self.indent = indent - self.fname = "" + self.fname = fname self.epaddr = 0 self.len = 0 self.ival = "" self.type = "" self.attr = 0 self.max = 0 + if self.fname: + self.read(self.fname) def read(self, fname): fullpath = ""
@@ -271,11 +273,11 @@ class UsbEndpoint: class UsbInterface: "Container for USB interface info" - def __init__(self, parent = None, level = 1): + def __init__(self, parent, fname, level=1): self.parent = parent self.level = level self.fullpath = "" - self.fname = "" + self.fname = fname self.iclass = 0 self.isclass = 0 self.iproto = 0
@@ -284,6 +286,9 @@ class UsbInterface: self.devname = "" self.protoname = "" self.eps = [] + if self.fname: + self.read(self.fname) + def read(self, fname): fullpath = "" if self.parent:
@@ -302,10 +307,9 @@ class UsbInterface: pass self.protoname = find_usb_class(self.iclass, self.isclass, self.iproto) if showeps: - for epfnm in os.listdir(prefix + fullpath): - if epfnm[:3] == "ep_": - ep = UsbEndpoint(self, self.level+len(self.fname)) - ep.read(epfnm) + for dirent in os.listdir(prefix + fullpath): + if dirent[:3] == "ep_": + ep = UsbEndpoint(self, dirent, self.level + len(self.fname)) self.eps.append(ep) def __str__(self):
@@ -326,10 +330,10 @@ class UsbInterface: class UsbDevice: "Container for USB device info" - def __init__(self, parent = None, level = 0): + def __init__(self, parent, fname, level=0): self.parent = parent self.level = level - self.fname = "" + self.fname = fname self.fullpath = "" self.iclass = 0 self.isclass = 0
@@ -346,6 +350,9 @@ class UsbDevice: self.devname = "" self.interfaces = [] self.children = [] + if self.fname: + self.read(self.fname) + self.readchildren() def read(self, fname): self.fname = fname
@@ -402,13 +409,10 @@ class UsbDevice: if not dirent[0:1].isdigit(): continue if os.access(prefix + dirent + "/bInterfaceClass", os.R_OK): - iface = UsbInterface(self, self.level+1) - iface.read(dirent) + iface = UsbInterface(self, dirent, self.level+1) self.interfaces.append(iface) else: - usbdev = UsbDevice(self, self.level+1) - usbdev.read(dirent) - usbdev.readchildren() + usbdev = UsbDevice(self, dirent, self.level+1) self.children.append(usbdev) usbsortkey = lambda obj: [int(x) for x in re.split(r"[-:.]", obj.fname)] self.interfaces.sort(key=usbsortkey)
@@ -438,8 +442,7 @@ class UsbDevice: else: strg += "\n" if showeps: - ep = UsbEndpoint(self, self.level+len(self.fname)) - ep.read("ep_00") + ep = UsbEndpoint(self, "ep_00", self.level+len(self.fname)) strg += str(ep) if showint: for iface in self.interfaces:
@@ -472,9 +475,7 @@ def read_usb(): for dirent in os.listdir(prefix): if not dirent[0:3] == "usb": continue - usbdev = UsbDevice(None, 0) - usbdev.read(dirent) - usbdev.readchildren() + usbdev = UsbDevice(None, dirent, 0) root_hubs.append(usbdev) root_hubs.sort(key=lambda x: int(x.fname[3:])) for usbdev in root_hubs:
Signature · 1 line
2.21.0
PATCH 24/34 lsusb.py: UsbEndpoint: indent is a class implementation detail
In reply to Mantas MikulėnasThe class knows how to format itself, so it should know how to indent itself, like the other two classes do.
--- lsusb.py.in | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
lsusb.py.in +6 -5
@@ -238,9 +238,9 @@ def find_dev(driver, usbname): class UsbEndpoint: "Container for USB endpoint info" - def __init__(self, parent, fname, indent=18): + def __init__(self, parent, fname, level): self.parent = parent - self.indent = indent + self.level = level self.fname = fname self.epaddr = 0 self.len = 0
@@ -266,8 +266,9 @@ class UsbEndpoint: self.max = int(readattr(fullpath, "wMaxPacketSize"), 16) def __str__(self): + indent = self.level + len(self.parent.fname) return "%-17s %s(EP) %02x: %s %s attr %02x len %02x max %03x%s\n" % \ - (" " * self.indent, cols[5], self.epaddr, self.type, + (" " * indent, cols[5], self.epaddr, self.type, self.ival, self.attr, self.len, self.max, cols[0])
@@ -309,7 +310,7 @@ class UsbInterface: if showeps: for dirent in os.listdir(prefix + fullpath): if dirent[:3] == "ep_": - ep = UsbEndpoint(self, dirent, self.level + len(self.fname)) + ep = UsbEndpoint(self, dirent, self.level+1) self.eps.append(ep) def __str__(self):
@@ -442,7 +443,7 @@ class UsbDevice: else: strg += "\n" if showeps: - ep = UsbEndpoint(self, "ep_00", self.level+len(self.fname)) + ep = UsbEndpoint(self, "ep_00", self.level+1) strg += str(ep) if showint: for iface in self.interfaces:
Signature · 1 line
2.21.0
PATCH 25/34 lsusb.py: a few cosmetic changes
In reply to Mantas Mikulėnas- Place all globals above functions.
- Do not need chr(), this is not Visual Basic.
- Use .startswith() instead of hardcoding the length.
--- lsusb.py.in | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-)
lsusb.py.in +15 -23
@@ -33,16 +33,18 @@ usbids = [ "/usr/share/libosinfo/usb.ids", "/usr/share/kcmusb/usb.ids", ] +cols = ("", "", "", "", "", "") -esc = chr(27) -norm = esc + "[0;0m" -bold = esc + "[0;1m" -red = esc + "[0;31m" -green= esc + "[0;32m" -amber= esc + "[0;33m" -blue = esc + "[0;34m" +norm = "\033[0;0m" +bold = "\033[0;1m" +red = "\033[0;31m" +green = "\033[0;32m" +amber = "\033[0;33m" +blue = "\033[0;34m" -cols = ("", "", "", "", "", "") +usbvendors = {} +usbproducts = {} +usbclasses = {} def readattr(path, name): "Read attribute from sysfs and return as string"
@@ -53,10 +55,6 @@ def readlink(path, name): "Read symlink and return basename" return os.path.basename(os.readlink(prefix + path + "/" + name)); -usbvendors = {} -usbproducts = {} -usbclasses = {} - def ishexdigit(str): "return True if all digits are valid hex digits" for dg in str:
@@ -309,15 +307,12 @@ class UsbInterface: self.protoname = find_usb_class(self.iclass, self.isclass, self.iproto) if showeps: for dirent in os.listdir(prefix + fullpath): - if dirent[:3] == "ep_": + if dirent.startswith("ep_"): ep = UsbEndpoint(self, dirent, self.level+1) self.eps.append(ep) def __str__(self): - if self.noep == 1: - plural = " " - else: - plural = "s" + plural = (" " if self.noep == 1 else "s") strg = "%-17s (IF) %02x:%02x:%02x %iEP%s (%s) %s%s %s%s%s\n" % \ (" " * self.level+self.fname, self.iclass, self.isclass, self.iproto, self.noep,
@@ -368,14 +363,14 @@ class UsbDevice: + readattr(fname, "product") except: pass - if self.name and self.name[:5] == "Linux": + if self.name: mch = re.match(r"Linux [^ ]* (.hci[_-]hcd) .HCI Host Controller", self.name) if mch: self.name = mch.group(1) if not self.name: self.name = find_usb_prod(self.vid, self.pid) # Some USB Card readers have a better name then Generic ... - if self.name[:7] == "Generic": + if self.name.startswith("Generic"): oldnm = self.name self.name = find_usb_prod(self.vid, self.pid) if not self.name:
@@ -429,10 +424,7 @@ class UsbDevice: else: col = cols[1] if not nohub or self.iclass != HUB_ICLASS: - if self.nointerfaces == 1: - plural = " " - else: - plural = "s" + plural = (" " if self.nointerfaces == 1 else "s") strg = "%-16s %s%04x:%04x%s %02x %s%6sMbit/s %5s %iIF%s (%s%s%s)" % \ (" " * self.level + self.fname, cols[1], self.vid, self.pid, cols[0],
Signature · 1 line
2.21.0
PATCH 26/34 lsusb.py: shorten find_usb_class()
In reply to Mantas Mikulėnas--- lsusb.py.in | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-)
lsusb.py.in +3 -7
@@ -141,13 +141,9 @@ def find_usb_prod(vid, pid): def find_usb_class(cid, sid, pid): "Return USB protocol from usbclasses list" lnlst = len(usbclasses) - cls = usbclasses.get((cid, sid, pid)) - if cls: - return str(cls) - cls = usbclasses.get((cid, sid, -1)) - if cls: - return str(cls) - cls = usbclasses.get((cid, -1, -1)) + cls = usbclasses.get((cid, sid, pid)) \ + or usbclasses.get((cid, sid, -1)) \ + or usbclasses.get((cid, -1, -1)) if cls: return str(cls) return ""
Signature · 1 line
2.21.0
PATCH 27/34 lsusb.py: give all Usb* objects a .path attribute
In reply to Mantas Mikulėnas--- lsusb.py.in | 77 +++++++++++++++++++++++++---------------------------- 1 file changed, 36 insertions(+), 41 deletions(-)
lsusb.py.in +36 -41
@@ -236,6 +236,7 @@ class UsbEndpoint: self.parent = parent self.level = level self.fname = fname + self.path = "" self.epaddr = 0 self.len = 0 self.ival = ""
@@ -246,18 +247,16 @@ class UsbEndpoint: self.read(self.fname) def read(self, fname): - fullpath = "" - if self.parent: - fullpath = self.parent.fullpath + "/" - fullpath += fname - self.epaddr = int(readattr(fullpath, "bEndpointAddress"), 16) - ival = int(readattr(fullpath, "bInterval"), 16) + self.fname = fname + self.path = self.parent.path + "/" + fname + self.epaddr = int(readattr(self.path, "bEndpointAddress"), 16) + ival = int(readattr(self.path, "bInterval"), 16) if ival: - self.ival = "(%s)" % readattr(fullpath, "interval") - self.len = int(readattr(fullpath, "bLength"), 16) - self.type = readattr(fullpath, "type") - self.attr = int(readattr(fullpath, "bmAttributes"), 16) - self.max = int(readattr(fullpath, "wMaxPacketSize"), 16) + self.ival = "(%s)" % readattr(self.path, "interval") + self.len = int(readattr(self.path, "bLength"), 16) + self.type = readattr(self.path, "type") + self.attr = int(readattr(self.path, "bmAttributes"), 16) + self.max = int(readattr(self.path, "wMaxPacketSize"), 16) def __str__(self): indent = self.level + len(self.parent.fname)
@@ -271,8 +270,8 @@ class UsbInterface: def __init__(self, parent, fname, level=1): self.parent = parent self.level = level - self.fullpath = "" self.fname = fname + self.path = "" self.iclass = 0 self.isclass = 0 self.iproto = 0
@@ -285,24 +284,20 @@ class UsbInterface: self.read(self.fname) def read(self, fname): - fullpath = "" - if self.parent: - fullpath += self.parent.fname + "/" - fullpath += fname - self.fullpath = fullpath self.fname = fname - self.iclass = int(readattr(fullpath, "bInterfaceClass"),16) - self.isclass = int(readattr(fullpath, "bInterfaceSubClass"),16) - self.iproto = int(readattr(fullpath, "bInterfaceProtocol"),16) - self.noep = int(readattr(fullpath, "bNumEndpoints")) + self.path = self.parent.path + "/" + fname + self.iclass = int(readattr(self.path, "bInterfaceClass"),16) + self.isclass = int(readattr(self.path, "bInterfaceSubClass"),16) + self.iproto = int(readattr(self.path, "bInterfaceProtocol"),16) + self.noep = int(readattr(self.path, "bNumEndpoints")) try: - self.driver = readlink(fname, "driver") - self.devname = find_dev(self.driver, fname) + self.driver = readlink(self.path, "driver") + self.devname = find_dev(self.driver, self.path) except: pass self.protoname = find_usb_class(self.iclass, self.isclass, self.iproto) if showeps: - for dirent in os.listdir(prefix + fullpath): + for dirent in os.listdir(prefix + self.path): if dirent.startswith("ep_"): ep = UsbEndpoint(self, dirent, self.level+1) self.eps.append(ep)
@@ -326,7 +321,7 @@ class UsbDevice: self.parent = parent self.level = level self.fname = fname - self.fullpath = "" + self.path = "" self.iclass = 0 self.isclass = 0 self.iproto = 0
@@ -348,15 +343,15 @@ class UsbDevice: def read(self, fname): self.fname = fname - self.fullpath = fname - self.iclass = int(readattr(fname, "bDeviceClass"), 16) - self.isclass = int(readattr(fname, "bDeviceSubClass"), 16) - self.iproto = int(readattr(fname, "bDeviceProtocol"), 16) - self.vid = int(readattr(fname, "idVendor"), 16) - self.pid = int(readattr(fname, "idProduct"), 16) + self.path = fname + self.iclass = int(readattr(self.path, "bDeviceClass"), 16) + self.isclass = int(readattr(self.path, "bDeviceSubClass"), 16) + self.iproto = int(readattr(self.path, "bDeviceProtocol"), 16) + self.vid = int(readattr(self.path, "idVendor"), 16) + self.pid = int(readattr(self.path, "idProduct"), 16) try: - self.name = readattr(fname, "manufacturer") + " " \ - + readattr(fname, "product") + self.name = readattr(self.path, "manufacturer") + " " \ + + readattr(self.path, "product") except: pass if self.name:
@@ -372,23 +367,23 @@ class UsbDevice: if not self.name: self.name = oldnm try: - ser = readattr(fname, "serial") + ser = readattr(self.path, "serial") # Some USB devs report "serial" as serial no. suppress if (ser and ser != "serial"): self.name += " " + ser except: pass - self.usbver = readattr(fname, "version") - self.speed = readattr(fname, "speed") - self.maxpower = readattr(fname, "bMaxPower") - self.noports = int(readattr(fname, "maxchild")) + self.usbver = readattr(self.path, "version") + self.speed = readattr(self.path, "speed") + self.maxpower = readattr(self.path, "bMaxPower") + self.noports = int(readattr(self.path, "maxchild")) try: - self.nointerfaces = int(readattr(fname, "bNumInterfaces")) + self.nointerfaces = int(readattr(self.path, "bNumInterfaces")) except: self.nointerfaces = 0 try: - self.driver = readlink(fname, "driver") - self.devname = find_dev(self.driver, fname) + self.driver = readlink(self.path, "driver") + self.devname = find_dev(self.driver, self.path) except: pass
Signature · 1 line
2.21.0
PATCH 28/34 lsusb.py: add an actual __repr__() to classes
In reply to Mantas MikulėnasThis simplifies debugging.
--- lsusb.py.in | 9 +++++++++ 1 file changed, 9 insertions(+)
lsusb.py.in +9 -0
@@ -258,6 +258,9 @@ class UsbEndpoint: self.attr = int(readattr(self.path, "bmAttributes"), 16) self.max = int(readattr(self.path, "wMaxPacketSize"), 16) + def __repr__(self): + return "<UsbEndpoint[%r]>" % self.fname + def __str__(self): indent = self.level + len(self.parent.fname) return "%-17s %s(EP) %02x: %s %s attr %02x len %02x max %03x%s\n" % \
@@ -302,6 +305,9 @@ class UsbInterface: ep = UsbEndpoint(self, dirent, self.level+1) self.eps.append(ep) + def __repr__(self): + return "<UsbInterface[%r]>" % self.fname + def __str__(self): plural = (" " if self.noep == 1 else "s") strg = "%-17s (IF) %02x:%02x:%02x %iEP%s (%s) %s%s %s%s%s\n" % \
@@ -405,6 +411,9 @@ class UsbDevice: self.interfaces.sort(key=usbsortkey) self.children.sort(key=usbsortkey) + def __repr__(self): + return "<UsbDevice[%r]>" % self.fname + def __str__(self): if self.iclass == HUB_ICLASS: col = cols[2]
Signature · 1 line
2.21.0
PATCH 29/34 lsusb.py: give all Usb* classes a superclass
In reply to Mantas Mikulėnas--- lsusb.py.in | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
lsusb.py.in +6 -3
@@ -230,7 +230,10 @@ def find_dev(driver, usbname): return res -class UsbEndpoint: +class UsbObject: + pass + +class UsbEndpoint(UsbObject): "Container for USB endpoint info" def __init__(self, parent, fname, level): self.parent = parent
@@ -268,7 +271,7 @@ class UsbEndpoint: self.ival, self.attr, self.len, self.max, cols[0]) -class UsbInterface: +class UsbInterface(UsbObject): "Container for USB interface info" def __init__(self, parent, fname, level=1): self.parent = parent
@@ -321,7 +324,7 @@ class UsbInterface: strg += str(ep) return strg -class UsbDevice: +class UsbDevice(UsbObject): "Container for USB device info" def __init__(self, parent, fname, level=0): self.parent = parent
Signature · 1 line
2.21.0
PATCH 30/34 lsusb.py: convert readattr() and readlink() to methods of the container
In reply to Mantas Mikulėnas--- lsusb.py.in | 69 +++++++++++++++++++++++++---------------------------- 1 file changed, 33 insertions(+), 36 deletions(-)
lsusb.py.in +33 -36
@@ -46,15 +46,6 @@ usbvendors = {} usbproducts = {} usbclasses = {} -def readattr(path, name): - "Read attribute from sysfs and return as string" - f = open(prefix + path + "/" + name); - return f.readline().rstrip("\n"); - -def readlink(path, name): - "Read symlink and return basename" - return os.path.basename(os.readlink(prefix + path + "/" + name)); - def ishexdigit(str): "return True if all digits are valid hex digits" for dg in str:
@@ -231,7 +222,13 @@ def find_dev(driver, usbname): class UsbObject: - pass + def read_attr(self, name): + path = prefix + self.path + "/" + name + return open(path).readline().rstrip("\n") + + def read_link(self, name): + path = prefix + self.path + "/" + name + return os.path.basename(os.readlink(path)) class UsbEndpoint(UsbObject): "Container for USB endpoint info"
@@ -252,14 +249,14 @@ class UsbEndpoint(UsbObject): def read(self, fname): self.fname = fname self.path = self.parent.path + "/" + fname - self.epaddr = int(readattr(self.path, "bEndpointAddress"), 16) - ival = int(readattr(self.path, "bInterval"), 16) + self.epaddr = int(self.read_attr("bEndpointAddress"), 16) + ival = int(self.read_attr("bInterval"), 16) if ival: - self.ival = "(%s)" % readattr(self.path, "interval") - self.len = int(readattr(self.path, "bLength"), 16) - self.type = readattr(self.path, "type") - self.attr = int(readattr(self.path, "bmAttributes"), 16) - self.max = int(readattr(self.path, "wMaxPacketSize"), 16) + self.ival = "(%s)" % self.read_attr("interval") + self.len = int(self.read_attr("bLength"), 16) + self.type = self.read_attr("type") + self.attr = int(self.read_attr("bmAttributes"), 16) + self.max = int(self.read_attr("wMaxPacketSize"), 16) def __repr__(self): return "<UsbEndpoint[%r]>" % self.fname
@@ -292,12 +289,12 @@ class UsbInterface(UsbObject): def read(self, fname): self.fname = fname self.path = self.parent.path + "/" + fname - self.iclass = int(readattr(self.path, "bInterfaceClass"),16) - self.isclass = int(readattr(self.path, "bInterfaceSubClass"),16) - self.iproto = int(readattr(self.path, "bInterfaceProtocol"),16) - self.noep = int(readattr(self.path, "bNumEndpoints")) + self.iclass = int(self.read_attr("bInterfaceClass"),16) + self.isclass = int(self.read_attr("bInterfaceSubClass"),16) + self.iproto = int(self.read_attr("bInterfaceProtocol"),16) + self.noep = int(self.read_attr("bNumEndpoints")) try: - self.driver = readlink(self.path, "driver") + self.driver = self.read_link("driver") self.devname = find_dev(self.driver, self.path) except: pass
@@ -353,14 +350,14 @@ class UsbDevice(UsbObject): def read(self, fname): self.fname = fname self.path = fname - self.iclass = int(readattr(self.path, "bDeviceClass"), 16) - self.isclass = int(readattr(self.path, "bDeviceSubClass"), 16) - self.iproto = int(readattr(self.path, "bDeviceProtocol"), 16) - self.vid = int(readattr(self.path, "idVendor"), 16) - self.pid = int(readattr(self.path, "idProduct"), 16) + self.iclass = int(self.read_attr("bDeviceClass"), 16) + self.isclass = int(self.read_attr("bDeviceSubClass"), 16) + self.iproto = int(self.read_attr("bDeviceProtocol"), 16) + self.vid = int(self.read_attr("idVendor"), 16) + self.pid = int(self.read_attr("idProduct"), 16) try: - self.name = readattr(self.path, "manufacturer") + " " \ - + readattr(self.path, "product") + self.name = self.read_attr("manufacturer") + " " \ + + self.read_attr("product") except: pass if self.name:
@@ -376,22 +373,22 @@ class UsbDevice(UsbObject): if not self.name: self.name = oldnm try: - ser = readattr(self.path, "serial") + ser = self.read_attr("serial") # Some USB devs report "serial" as serial no. suppress if (ser and ser != "serial"): self.name += " " + ser except: pass - self.usbver = readattr(self.path, "version") - self.speed = readattr(self.path, "speed") - self.maxpower = readattr(self.path, "bMaxPower") - self.noports = int(readattr(self.path, "maxchild")) + self.usbver = self.read_attr("version") + self.speed = self.read_attr("speed") + self.maxpower = self.read_attr("bMaxPower") + self.noports = int(self.read_attr("maxchild")) try: - self.nointerfaces = int(readattr(self.path, "bNumInterfaces")) + self.nointerfaces = int(self.read_attr("bNumInterfaces")) except: self.nointerfaces = 0 try: - self.driver = readlink(self.path, "driver") + self.driver = self.read_link("driver") self.devname = find_dev(self.driver, self.path) except: pass
Signature · 1 line
2.21.0
PATCH 31/34 lsusb.py: use color by default
In reply to Mantas Mikulėnas--- lsusb.py.in | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-)
lsusb.py.in +13 -2
@@ -456,6 +456,7 @@ def usage(): print(" -u, --hide-empty-hubs suppress empty hubs") print(" -U, --hide-hubs suppress all hubs") print(" -c, --color use colors") + print(" -C, --no-color disable colors") print(" -e, --endpoints display endpoint info") print(" -f FILE, --usbids-path FILE") print(" override filename for /usr/share/usb.ids")
@@ -478,6 +479,7 @@ def main(argv): "main entry point" global showint, showhubint, noemptyhub, nohub global cols, usbids, showeps + usecols = None long_options = [ "help",
@@ -486,12 +488,13 @@ def main(argv): "hide-empty-hubs", "hide-hubs", "color", + "no-color", "usbids-path=", "endpoints", ] try: - (optlist, args) = getopt.gnu_getopt(argv[1:], "hiIuUwcef:", long_options) + (optlist, args) = getopt.gnu_getopt(argv[1:], "hiIuUwcCef:", long_options) except getopt.GetoptError as exc: print("Error:", exc, file=sys.stderr) sys.exit(2)
@@ -510,7 +513,9 @@ def main(argv): noemptyhub = True nohub = True elif opt[0] in {"-c", "--color"}: - cols = (norm, bold, red, green, amber, blue) + usecols = True + elif opt[0] in {"-C", "--no-color"}: + usecols = False elif opt[0] == "-w": print("Warning: option -w is no longer supported", file=sys.stderr) elif opt[0] in {"-f", "--usbids-path"}:
@@ -521,6 +526,12 @@ def main(argv): print("Error: excess args %s ..." % args[0], file=sys.stderr) sys.exit(2) + if usecols is None: + usecols = sys.stdout.isatty() and os.environ.get("TERM", "dumb") != "dumb" + + if usecols: + cols = (norm, bold, red, green, amber, blue) + if usbids[0]: try: parse_usb_ids()
Signature · 1 line
2.21.0
PATCH 32/34 lsusb.py: rework output for more consistent indent of both columns
In reply to Mantas Mikulėnas--- lsusb.py.in | 54 ++++++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 25 deletions(-)
lsusb.py.in +29 -25
@@ -46,6 +46,9 @@ usbvendors = {} usbproducts = {} usbclasses = {} +def colorize(num, text): + return cols[num] + str(text) + cols[0] + def ishexdigit(str): "return True if all digits are valid hex digits" for dg in str:
@@ -262,10 +265,13 @@ class UsbEndpoint(UsbObject): return "<UsbEndpoint[%r]>" % self.fname def __str__(self): - indent = self.level + len(self.parent.fname) - return "%-17s %s(EP) %02x: %s %s attr %02x len %02x max %03x%s\n" % \ - (" " * indent, cols[5], self.epaddr, self.type, - self.ival, self.attr, self.len, self.max, cols[0]) + indent = " " * self.level + #name = "%s/ep_%02X" % (self.parent.fname, self.epaddr) + name = "" + body = "(EP) %02x: %s %s attr %02x len %02x max %03x" % \ + (self.epaddr, self.type, self.ival, self.attr, self.len, self.max) + body = colorize(5, body) + return "%-17s %s\n" % (indent + name, indent + body) class UsbInterface(UsbObject):
@@ -309,13 +315,13 @@ class UsbInterface(UsbObject): return "<UsbInterface[%r]>" % self.fname def __str__(self): + indent = " " * self.level + name = self.fname plural = (" " if self.noep == 1 else "s") - strg = "%-17s (IF) %02x:%02x:%02x %iEP%s (%s) %s%s %s%s%s\n" % \ - (" " * self.level+self.fname, self.iclass, - self.isclass, self.iproto, self.noep, - plural, self.protoname, - cols[3], self.driver, - cols[4], self.devname, cols[0]) + body = "(IF) %02x:%02x:%02x %iEP%s (%s) %s %s" % \ + (self.iclass, self.isclass, self.iproto, self.noep, plural, + self.protoname, colorize(3, self.driver), colorize(4, self.devname)) + strg = "%-17s %s\n" % (indent + name, indent + body) if showeps and self.eps: for ep in self.eps: strg += str(ep)
@@ -415,25 +421,23 @@ class UsbDevice(UsbObject): return "<UsbDevice[%r]>" % self.fname def __str__(self): - if self.iclass == HUB_ICLASS: - col = cols[2] + is_hub = (self.iclass == HUB_ICLASS) + if is_hub: if noemptyhub and len(self.children) == 0: return "" - if nohub: - strg = "" - else: - col = cols[1] - if not nohub or self.iclass != HUB_ICLASS: + strg = "" + if not (nohub and is_hub): + indent = " " * self.level + name = self.fname plural = (" " if self.nointerfaces == 1 else "s") - strg = "%-16s %s%04x:%04x%s %02x %s%6sMbit/s %5s %iIF%s (%s%s%s)" % \ - (" " * self.level + self.fname, - cols[1], self.vid, self.pid, cols[0], + body = "%s %02x %s%5sMBit/s %s %iIF%s (%s) %s" % \ + (colorize(1, "%04x:%04x" % (self.vid, self.pid)), self.iclass, self.usbver, self.speed, self.maxpower, - self.nointerfaces, plural, col, self.name, cols[0]) - if self.iclass == HUB_ICLASS and not showhubint: - strg += " %shub%s\n" % (cols[2], cols[0]) - else: - strg += "\n" + self.nointerfaces, plural, + colorize(2 if is_hub else 1, self.name), + colorize(2, "hub") if is_hub else "") + strg = "%-17s %s\n" % (indent + name, indent + body) + if not (is_hub and not showhubint): if showeps: ep = UsbEndpoint(self, "ep_00", self.level+1) strg += str(ep)
Signature · 1 line
2.21.0
PATCH 33/34 lsusb.py: fix endpoint interval spacing
In reply to Mantas Mikulėnas--- lsusb.py.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
lsusb.py.in +2 -2
@@ -255,7 +255,7 @@ class UsbEndpoint(UsbObject): self.epaddr = int(self.read_attr("bEndpointAddress"), 16) ival = int(self.read_attr("bInterval"), 16) if ival: - self.ival = "(%s)" % self.read_attr("interval") + self.ival = " (%s)" % self.read_attr("interval") self.len = int(self.read_attr("bLength"), 16) self.type = self.read_attr("type") self.attr = int(self.read_attr("bmAttributes"), 16)
@@ -268,7 +268,7 @@ class UsbEndpoint(UsbObject): indent = " " * self.level #name = "%s/ep_%02X" % (self.parent.fname, self.epaddr) name = "" - body = "(EP) %02x: %s %s attr %02x len %02x max %03x" % \ + body = "(EP) %02x: %s%s attr %02x len %02x max %03x" % \ (self.epaddr, self.type, self.ival, self.attr, self.len, self.max) body = colorize(5, body) return "%-17s %s\n" % (indent + name, indent + body)
Signature · 1 line
2.21.0
PATCH 34/34 lsusb.py: visually group USB-version-related fields
In reply to Mantas Mikulėnas--- lsusb.py.in | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
lsusb.py.in +3 -3
@@ -430,10 +430,10 @@ class UsbDevice(UsbObject): indent = " " * self.level name = self.fname plural = (" " if self.nointerfaces == 1 else "s") - body = "%s %02x %s%5sMBit/s %s %iIF%s (%s) %s" % \ + body = "%s %02x %iIF%s [USB %s, %5s Mbps, %5s] (%s) %s" % \ (colorize(1, "%04x:%04x" % (self.vid, self.pid)), - self.iclass, self.usbver, self.speed, self.maxpower, - self.nointerfaces, plural, + self.iclass, self.nointerfaces, plural, + self.usbver.strip(), self.speed, self.maxpower, colorize(2 if is_hub else 1, self.name), colorize(2, "hub") if is_hub else "") strg = "%-17s %s\n" % (indent + name, indent + body)
Signature · 1 line
2.21.0
Greg KH
maintainerRe: [PATCH 05/34] lsusb.py: remove -w (warn if usb.ids not sorted) option
In reply to Mantas MikulėnasQuoted 4 lines · Mantas Mikulėnas
Signed-off-by Mantas Mikulėnas <[email protected]>--- lsusb.py.in | 45 ++------------------------------------------- 1 file changed, 2 insertions(+), 43 deletions(-)
Why remove this? What's wrong with this option for people who want to work on usb.ids?
thanks,
greg k-h
Re: [PATCH 05/34] lsusb.py: remove -w (warn if usb.ids not sorted) option
Quoted 9 lines · Greg KH
Quoted 4 lines · Mantas Mikulėnas
Signed-off-by Mantas Mikulėnas <[email protected]>--- lsusb.py.in | 45 ++------------------------------------------- 1 file changed, 2 insertions(+), 43 deletions(-)Why remove this? What's wrong with this option for people who want to work on usb.ids?
Hmm, I was under the impression that its purpose was just for debugging the lookup code and becomes unnecessary when said lookup code is outright removed (the next commit removes the binary-search lookup). Did I misunderstand the code?
(Although in any case, a dedicated "lint-usb.ids" script seems like a more fitting place for this feature than a lsusb option...)
Signature · 1 line
Mantas Mikulėnas
Greg KH
maintainerRe: [PATCH 05/34] lsusb.py: remove -w (warn if usb.ids not sorted) option
Quoted 12 lines · Mantas Mikulėnas
Quoted 9 lines · Greg KH
Quoted 4 lines · Mantas Mikulėnas
Signed-off-by Mantas Mikulėnas <[email protected]>--- lsusb.py.in | 45 ++------------------------------------------- 1 file changed, 2 insertions(+), 43 deletions(-)Why remove this? What's wrong with this option for people who want to work on usb.ids?
Quoted 7 lines
Hmm, I was under the impression that its purpose was just for debugging the lookup code and becomes unnecessary when said lookup code is outright removed (the next commit removes the binary-search lookup). Did I misunderstand the code?
(Although in any case, a dedicated "lint-usb.ids" script seems like a more fitting place for this feature than a lsusb option...)
Yes, lint-usb.ids does make much more sense. I'll apply this one now, thanks.
greg k-h
Greg KH
maintainerRe: [PATCH 18/34] lsusb.py: use 'elif' where suitable
In reply to Mantas MikulėnasQuoted 11 lines · Mantas Mikulėnas
Signed-off-by Mantas Mikulėnas <[email protected]>--- lsusb.py.in | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-)lsusb.py.in +0
-0@@ -12,7 +12,10 @@
lsusb.py.in line 21
Quoted 10 lines
lsusb.py.in +4
-1# Py2 compat from __future__ import print_function -import os, sys, re, getopt +import getopt +import os +import re +import sys # Global options showint = False
That change wasn't part of the "elif" changes, but it's ok, you've done a lot here :)
Greg KH
maintainerRe: [PATCH 08/34] lsusb.py: do not entirely hide usb.ids exceptions
In reply to Mantas MikulėnasQuoted 10 lines · Mantas Mikulėnas
Signed-off-by Mantas Mikulėnas <[email protected]>--- lsusb.py.in | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)lsusb.py.in +0
-0
lsusb.py.in def main(argv): · line 614
Quoted 8 lines
lsusb.py.in +2
-3@@ -610,9 +610,8 @@ def main(argv): if usbids[0]: try: parse_usb_ids() - except: - print(" WARNING: Failure to read usb.ids", file=sys.stderr) - #print(sys.exc_info(), file=sys.stderr) + except IOError as e: + print("Warning: Failure to read usb.ids:", e, file=sys.stderr)
This patch is a bit "annoying" in that now I see the error:
Warning: Failure to read usb.ids: [Errno 2] No such file or directory: '/usr/share/kcmusb/usb.ids'
When I never would care about /usr/share/kcmusb, the "problem" is that the usb.ids file is no where in any of the other "default" choices in the system.
So I suggest either saying "here's all the places I did not find it", or just stick to the error that we have today, as this feels worse to me.
thanks,
greg k-h
Greg KH
maintainerQuoted 5 lines · Mantas Mikulėnas
Hi,
I accidentally ended up hacking on the
lsusb.pyscript and now have an assorted collection of patches:
Quoted 10 lines
- Output (controllers, hubs, etc.) sorted numerically.
- Color enabled by default when on a tty.
- Added --long-options.
- Replaced hand-rolled binary search with ordinary dict lookups; lost the -w (--warn-if-unsorted) option in the process.
- Cosmetic changes to make it look more like Python and less like C.
- Some changes to the output formatting that I liked to have in my own local version.
I've applied all of these patches now, except for the usb.ids error message that I responded to. Note, I do not know python well, if at all, so I just had to take your word for most of these :)
I don't like the usb.ids error message that happens here, it's not essential that that file be found, especially given that most distros do not ship it anymore as they have switched over to the hw database format. So maybe we can just drop the "error" as the tool does work without it, or look for the hwids data instead?
thanks,
greg k-h
Re: [PATCH 08/34] lsusb.py: do not entirely hide usb.ids exceptions
In reply to Greg KHQuoted 28 lines · Greg KH
Quoted 10 lines · Mantas Mikulėnas
Signed-off-by Mantas Mikulėnas <[email protected]>--- lsusb.py.in | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)lsusb.py.in +0
-0lsusb.py.in def main(argv): · line 614
Quoted 8 lines
lsusb.py.in +2
-3@@ -610,9 +610,8 @@ def main(argv): if usbids[0]: try: parse_usb_ids() - except: - print(" WARNING: Failure to read usb.ids", file=sys.stderr) - #print(sys.exc_info(), file=sys.stderr) + except IOError as e: + print("Warning: Failure to read usb.ids:", e, file=sys.stderr)This patch is a bit "annoying" in that now I see the error:
Warning: Failure to read usb.ids: [Errno 2] No such file or directory: '/usr/share/kcmusb/usb.ids'When I never would care about
/usr/share/kcmusb, the "problem" is that the usb.ids file is no where in any of the other "default" choices in the system.
Quoted 6 lines
So I suggest either saying "here's all the places I did not find it", or just stick to the error that we have today, as this feels worse to me.
thanks,
greg k-h
Ah, I guess I'll have to redo that. Maybe it would be best to suppress errors for default paths, but still show them for user-specified paths (--usbids-path)?
(Actually, I assumed @usbids@ as the 1st item would be substituted on most systems. However, I don't quite understand why e.g. the KDE kcmusb path was added here... Is the list meant to have all possible paths, or is it meant to require the distro to specify the path? It's currently a mix of both.)
Signature · 1 line
Mantas Mikulėnas
Quoted 22 lines · Greg KH
Quoted 5 lines · Mantas Mikulėnas
Hi,
I accidentally ended up hacking on the
lsusb.pyscript and now have an assorted collection of patches:Quoted 10 lines
- Output (controllers, hubs, etc.) sorted numerically.
- Color enabled by default when on a tty.
- Added --long-options.
- Replaced hand-rolled binary search with ordinary dict lookups; lost the -w (--warn-if-unsorted) option in the process.
- Cosmetic changes to make it look more like Python and less like C.
- Some changes to the output formatting that I liked to have in my own local version.I've applied all of these patches now, except for the usb.ids error message that I responded to. Note, I do not know python well, if at all, so I just had to take your word for most of these :)
Quoted 5 lines
I don't like the usb.ids error message that happens here, it's not essential that that file be found, especially given that most distros do not ship it anymore as they have switched over to the hw database format. So maybe we can just drop the "error" as the tool does work without it, or look for the hwids data instead?
Yeah, it's probably fine to drop it (especially because the v010 parser bugs that prompted the change had already received fixes in master).
I do want to make the tool use hwdb (I suppose the dependency is fine given that lsusb.c already uses it), but as the only existing parser for hwdb.bin is the C library with cpp macros sprinkled on top, I suspect doing it from python will hurt a bit.
Signature · 1 line
Mantas Mikulėnas