""" Using dbus, listen for network interface changes and update the internet usage type='signal', interface='org.freedesktop.NetworkManager' It writes disconnect and connect times to a file """ from pydbus import SystemBus from gi.repository import GLib import datetime # The path to the file where the internet usage is stored. USAGE_FILE = "/home/inex/dev/Linux/internet_usage/usage.txt" session_bus = SystemBus() loop = GLib.MainLoop() def handle_state_change(state): if state == 70: # The network interface is connected. # Write the current time to the file. with open(USAGE_FILE, "a") as usage_file: usage_file.write(f"{datetime.datetime.now()} CONNECT\n") elif state == 50: # The network interface is disconnected. # Write the current time to the file. with open(USAGE_FILE, "a") as usage_file: usage_file.write(f"{datetime.datetime.now()} DISCONNECT\n") # Get the NetworkManager object. nm = session_bus.get("org.freedesktop.NetworkManager") nm.StateChanged.connect(handle_state_change) loop.run()