正在处理以下示例代码,以使用pyudev检索连接的HDD详细信息。
我正在尝试探测的设备:
使用以下脚本,我可以检索USB记忆棒信息。但是,当我连接 USB到SATA转换器时,我得到转换器的序列号而不是HDD。此外,对于我的常规SATA硬盘驱动器,我在“ID_VENDOR”上获得例外。
示例输出:
Device Connected Info:
[Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.1/2-1.1:1.0/host9/target9:0:0/9:0:0:0/block/sdc'),
Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/host7/target7:0:0/7:0:0:0/block/sdb'),
Device(u'/sys/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda')]
Device Information:
SonyPendrive:
{'model': u'Storage Media', 'vendor': u'Sony', 'serial': u'CB071031B7E215C294'}
SATA IDE Converter
{'model': u'DE SATA Device', 'vendor': u'USB TO I', 'serial': u'000000000033'}
Regular HDD
Traceback (most recent call last):
File "t.py", line 52, in <module>
devInfo=decode_device_info(deviceRef)
File "t.py", line 9, in decode_device_info
vendor = device['ID_VENDOR'].replace('_',' ')
File "/home/srivathsan/Desktop/pyudev-pyudev-3a26e05/pyudev/device.py", line 831, in __getitem__
raise KeyError(property)
KeyError: 'ID_VENDOR'
示例代码:
import glib
from pyudev import Context, Monitor
def decode_device_info(device):
''' Accept a device. Return a dict of attributes of given device.
Clean up all strings in the process and make pretty.
'''
vendor = device['ID_VENDOR'].replace('_',' ')
model = device['ID_MODEL'].replace('_',' ')
try:
serial = device['ID_SERIAL_SHORT']
except:
serial = device['ID_SERIAL']
return({'vendor':vendor, 'model':model, 'serial':serial})
def getDevicelist(udevContext):
devices=[]
for device in udevContext.list_devices(subsystem='block', DEVTYPE='disk'):
# Filter out cd drives, loop devices.
if device.get('ID_TYPE', '') == 'cd':
continue
if device.get('UDISKS_PRESENTATION_NOPOLICY', '0') == '1':
continue
devices.append(device)
return devices
try:
from pyudev.glib import MonitorObserver
def device_event(observer, device):
print 'event {0} on device {1}'.format(device.action, device)
except:
from pyudev.glib import GUDevMonitorObserver as MonitorObserver
def device_event(observer, action, device):
print 'event {0} on device {1}'.format(action, device)
context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='block')
observer = MonitorObserver(monitor)
observer.connect('device-event', device_event)
monitor.start()
devicesConnected=getDevicelist(context)
if (devicesConnected):
print devicesConnected
for deviceRef in devicesConnected:
devInfo=decode_device_info(deviceRef)
print devInfo
glib.MainLoop().run()
有没有我缺少的参数。请给我一些指示。
答案 0 :(得分:0)
对于您获得的KeyError
,您可以替换
vendor = device['ID_VENDOR'].replace('_',' ')
以下之一:
try:
vendor = device['ID_VENDOR'].replace('_',' ')
except KeyError:
vendor = ""
或
vendor = device.get('ID_VENDOR', '').replace('_',' ')
或
if 'ID_VENDOR' in device:
vendor = device['ID_VENDOR'].replace('_',' ')
else:
vendor = ""
但是,我担心我不知道如何使用pyudev
来超越&#39; USB / SATA转换器连接到它的设备。