python udisks - enumerating device information

邮差的信 提交于 2019-11-28 10:19:22
mark

You can use Udisks via dbus directly in python.

import dbus

bus = dbus.SystemBus()
ud_manager_obj = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks")
ud_manager = dbus.Interface(ud_manager_obj, 'org.freedesktop.UDisks')

for dev in ud_manager.EnumerateDevices():
    device_obj = bus.get_object("org.freedesktop.UDisks", dev)
    device_props = dbus.Interface(device_obj, dbus.PROPERTIES_IFACE)
    print device_props.Get('org.freedesktop.UDisks.Device', "DriveVendor")
    print device_props.Get('org.freedesktop.UDisks.Device', "DeviceMountPaths")
    print device_props.Get('org.freedesktop.UDisks.Device', "DriveSerial")
    print device_props.Get('org.freedesktop.UDisks.Device', "PartitionSize")

The full list of properties available is here http://hal.freedesktop.org/docs/udisks/Device.html

If all else fails you could parse the output of udisks. Here's an example script in Python3.2:

from subprocess import check_output as qx
from configparser import ConfigParser

def parse(text):
    parser = ConfigParser()
    parser.read_string("[DEFAULT]\n"+text)
    return parser['DEFAULT']

def udisks_info(device):
    # get udisks output
    out = qx(['udisks', '--show-info', device]).decode()

    # strip header & footer
    out = out[out.index('\n')+1:]
    i = out.find('=====')
    if i != -1: out = out[:i] 

    return parse(out)

info = udisks_info('/dev/sda1')
print("size = {:.2f} GiB".format(info.getint('size')/2**30))
print("""mount point = {mount paths}
uuid = {uuid}""".format_map(info))

# complex values could be parsed too
info = udisks_info('/dev/sda')
drive_data = info['drive'].replace('ports:\n', 'ports:\n  ')
print('serial =', parse(drive_data)['serial'])

Output

size = 57.15 GiB
mount point = /
uuid = b1812c6f-3ad6-40d5-94a6-1575b8ff02f0
serial = N31FNPH8
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!