一直在处理下面的示例代码,以使用pyudev检索连接的HDD详细信息。
我试图探测的设备:
- 普通sata硬盘
- USB到SATA转换器
- USB记忆棒
通过下面的脚本,我已经能够检索U盘信息。但是,当我连接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()
我缺少什么参数吗。请给我一些建议。
对于您获得的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
将USB/SATA转换器"超越"到与其连接的设备。