Hatena::ブログ(Diary)

kawa1128の日記 このページをアンテナに追加 RSSフィード Twitter

2009-06-08

PyUSBで、機器名称の取得

ちょこっとした理由でPythonからPCに接続されているUSBの機器名を取得したくなった。

ググっても、なかなか、出てこなかったので、備忘録がわりに。

#!/usr/local/bin/python

import usb

class UsbDevice(object):
    def __init__(self, vendor_id=None, product_id=None):
	busses = usb.busses()
	for bus in busses:
	    devices = bus.devices
	    for device in devices:
		if (device.idVendor, device.idProduct) == (vendor_id, product_id):
		    self.device = device
		    self.configuration = self.device.configurations[0]
		    self.interface = self.configuration.interfaces[0][0]
		    self.endpoints = []
		    self.pipes = []
		    for endpoint in self.interface.endpoints:
			self.endpoints.append(endpoint)
			self.pipes.append(endpoint.address)
		    return
	raise RuntimeError, 'Device not found'

    def open(self):
	if hasattr(self, 'handle'):
	    raise RuntimeError, 'Device already opened'
	self.handle = self.device.open()
	product = self.handle.getString(self.device.iProduct, 20)
	manufacturer = self.handle.getString(self.device.iManufacturer, 20)
	print product, manufacturer

    def close(self):
	if hasattr(self, 'handle'):
	    self.handle.releaseInterface()
	    del self.handle
	else:
	    raise RuntimeError, 'Device not opened'


def main():
    dev = UsbDevice(0x04fe, 0x0008)
    dev.open()
#    dev.close()

if __name__ == '__main__':
    main()

getStringの第2引数に文字数を指定してるけど、これは、libusbがCで書かれているなごりかな。ソースを読んでいないのでわかりませんが。

はてなユーザーのみコメントできます。はてなへログインもしくは新規登録をおこなってください。

トラックバック - http://d.hatena.ne.jp/kawa1128/20090608/1244439834