amartin94
amartin94

Reputation: 515

How to get usb serial number python

Ive been searching around for a little while and this is winding me up... This was easy in C# :/

Anyways.. I found this code, which is the closest i got, but i suck at Regular Expressions, so if someone could narrow that down for me so it isolates only the device ID's for each of the devices, then that would be awesome! Anyways, here's the code:

import re
import subprocess

device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>    \w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb", shell=True)
devices = []
for i in df.split('\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'),       dinfo.pop('device'))
            devices.append(dinfo)
print devices

Upvotes: 0

Views: 3497

Answers (2)

jaime
jaime

Reputation: 2344

The code below gives you only the device ids.

import pprint
import subprocess

df = subprocess.check_output('lsusb', shell=True)
device_ids = []
for line in filter(lambda s: s.startswith('Bus'), df.split('\n')):
    businfo, id, _ = line.split(':')
    id = id.split()[1]
    device_ids.append(id)

pprint.pprint(device_ids)

Upvotes: 1

Adrian Nicolaiev
Adrian Nicolaiev

Reputation: 51

Try this way:

import re
import subprocess
device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb", shell=True)
for i in df.split('\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            # Uncomment if you wish tags too
            #print dinfo.pop('tag')
            print dinfo.pop('id')

Upvotes: 1

Related Questions