pythonpython-3.xlinuxdbusnetworkmanager

Get property of DBus interface in Python


I would like to check current network connection is metered or not. In the Bash I can run:

qdbus --system org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.NetworkManager.Metered

But I want do it in Python.

I wrote a piece of code that gets the necessary interface:

import dbus

bus = dbus.SystemBus()
interface = dbus.Interface(
    bus.get_object(
        'org.freedesktop.NetworkManager',
        '/org/freedesktop/NetworkManager'
    ),
    dbus_interface='org.freedesktop.NetworkManager'
)

And I can get any method, such as GetDevices():

method = interface.get_dbus_method('GetDevices')

And it works (print(method())):

dbus.Array([dbus.ObjectPath('/org/freedesktop/NetworkManager/Devices/1'), dbus.ObjectPath('/org/freedesktop/NetworkManager/Devices/2'), dbus.ObjectPath('/org/freedesktop/NetworkManager/Devices/14')], signature=dbus.Signature('o'))

But how do I get the Metered property?


Solution

  • I would suggest you look at the more modern D-Bus libraries that are around and try to be more pythonic in how they work. I personally find pydbus very easy to get up and running with.

    from pydbus import SystemBus
    
    bus = SystemBus()
    network_manager = bus.get('org.freedesktop.NetworkManager')
    print("Metered is:", network_manager.Metered)
    

    If you want to do it with the dbus library then it would be like this:

    import dbus
    bus = dbus.SystemBus()
    
    network_manager_props = dbus.Interface(bus.get_object(
        'org.freedesktop.NetworkManager',
        '/org/freedesktop/NetworkManager'),
        dbus.PROPERTIES_IFACE)
    
    metered = network_manager_props.Get(
                "org.freedesktop.NetworkManager", 'Metered')
    print("Metered is:", metered)