要使用 python-gi 执行与 python-dbus 脚本等效的操作,以下内容对我有用:
from gi.repository import GLib, Gio
def network_changed_hndlr(network_monitor, network_available):
print(network_monitor)
print(network_available)
default = Gio.NetworkMonitor.get_default()
default.connect('network-changed', network_changed_hndlr)
mainloop = GLib.MainLoop()
try:
mainloop.run()
except KeyboardInterrupt:
mainloop.quit()
这是使用以下文档:
https ://lazka.github.io/pgi-docs/Gio-2.0/structs/NetworkMonitor.html
对于NetworkManager
有更多的对象路径和接口。
例如,如果我查看它的输出,
busctl tree org.freedesktop.NetworkManager
我可以监控 48 个项目。
如果我想监视活动连接的输出,它将是:
from gi.repository import GLib, Gio
ACTIVE_IFACE = 'org.freedesktop.NetworkManager.Connection.Active'
def active_network_hndlr(dbus_proxy, properties_changed, properties_removed):
props = properties_changed.unpack()
print(props)
def network_proxy(connection):
"""
Provide proxy for comfortable and pythonic method calls
"""
return Gio.DBusProxy.new_for_bus_sync(
bus_type=Gio.BusType.SYSTEM,
flags=Gio.DBusProxyFlags.NONE,
info=None,
name='org.freedesktop.NetworkManager',
object_path=connection,
interface_name=ACTIVE_IFACE,
cancellable=None)
net_mngr = network_proxy('/org/freedesktop/NetworkManager/ActiveConnection/8')
net_mngr.connect('g-properties-changed', active_network_hndlr)
mainloop = GLib.MainLoop()
try:
mainloop.run()
except KeyboardInterrupt:
mainloop.quit()
随着DBusProxy
做大部分繁重的工作。这记录在:
https ://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html