Skip to content

Instantly share code, notes, and snippets.

@rakslice
Created July 19, 2017 21:43
Show Gist options
  • Save rakslice/cfcec909e67f1461fbbdaeb41395139f to your computer and use it in GitHub Desktop.
Save rakslice/cfcec909e67f1461fbbdaeb41395139f to your computer and use it in GitHub Desktop.
Find the /sys/bus/usb/devices subdirectory for a device
#!/usr/bin/python
""" Find the /sys/bus/usb/devices subdirectory for a device """
import argparse
import os
import sys
DEVICES_DIR="/sys/bus/usb/devices"
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--device", "-d", help="ID for the device in the form abcd:abcd", required=True)
return parser.parse_args()
def die(msg):
print >> sys.stderr, msg
sys.exit(1)
def contents(filename):
with open(filename, "r") as handle:
return handle.read()
def chomp(s, ending=None):
if ending is None:
ending = "\n"
assert s.endswith(ending)
return s[:-len(ending)]
def main():
options = parse_args()
if len(options.device) != 9 or options.device[4] != ":":
die("Expected device value in the form xxxx:xxxx")
id_vendor = options.device[:4].lower()
id_product = options.device[-4:].lower()
for dirname_proper in os.listdir(DEVICES_DIR):
dirname = os.path.join(DEVICES_DIR, dirname_proper)
if not os.path.isdir(dirname):
continue
if not all(os.path.exists(os.path.join(dirname, x)) for x in ("idProduct", "idVendor")):
continue
cur_id_vendor = chomp(contents(os.path.join(dirname, "idVendor"))).lower()
if cur_id_vendor != id_vendor:
continue
cur_id_product = chomp(contents(os.path.join(dirname, "idProduct"))).lower()
#print "%s:%s -> %s" % (cur_id_product, cur_id_vendor, dirname_proper)
if cur_id_product == id_product:
print dirname
break
else:
die("Device %s not found" % options.device)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment