Bobblet
Bobblet

Reputation: 61

Get Serial Number of USB device with Python 3

I have been using pyusb to access the detail of a printer plugged in via USB. I currently have the following code working, but it appears that different devices require a different index. Here is my current code:

import usb

dev = usb.core.find(idProduct=0x001f)
print(usb.util.get_string(dev,256,3))

dev2 = usb.core.find(idProduct=0x0009)
print(usb.util.get_string(dev2,256,3))

The code for dev works perfectly, outputting a serial number, but dev2 outputs 'Zebra,' the manufacturer name. If I change 3 to either 6 or 7 it works, but then the first dev returns an error.

One solution in Python 2 is to use print(dev.serial_number), but in the serial_number attribute doesn't appear to exist in pyusb for Python 3.

Is there a way to get this working reliably for all devices? Thanks.

Upvotes: 5

Views: 12551

Answers (1)

Sun Bear
Sun Bear

Reputation: 8297

For the present PyUSB version 1.0.2, I found the correct syntax to answer this question to be:

import usb

dev = usb.core.find(idProduct=0x001f)
print( usb.util.get_string( dev, dev.iSerialNumber ) )

dev2 = usb.core.find(idProduct=0x0009)
print( usb.util.get_string( dev2, dev2.iSerialNumber ) )

Upvotes: 7

Related Questions