Real-time Wi-Fi Data | Network Usage Monitor using Python


The provided code is a Python script that monitors network usage in real-time using the psutil library. Let's go through the code and explain each part:

  1. import psutil
  2. import time

  3. def convert_bytes(bytes):
  4. """
  5. Convert bytes to a human-readable format.
  6. """
  7. sizes = ["B", "KB", "MB", "GB", "TB"]
  8. i = 0
  9. while bytes >= 1024 and i < len(sizes)-1:
  10. bytes /= 1024
  11. i += 1
  12. return f"{bytes:.2f} {sizes[i]}"

  13. def monitor_network_usage():
  14. """
  15. Monitor network usage in real-time.
  16. """
  17. old_value = psutil.net_io_counters().bytes_recv + psutil.net_io_counters().bytes_sent
  18. total_bytes = 0

  19. while True:
  20. new_value = psutil.net_io_counters().bytes_recv + psutil.net_io_counters().bytes_sent
  21. diff = new_value - old_value
  22. old_value = new_value
  23. total_bytes += diff

  24. print(f"\rNetwork Usage: {convert_bytes(diff)}/s | Total Data Usage: {convert_bytes(total_bytes)}", end="")
  25. time.sleep(1)

  26. if __name__ == "__main__":
  27. monitor_network_usage()

  • The script begins by importing the necessary modules: psutil for accessing system information and time for introducing delays in the script.
  • Next, there is a helper function called convert_bytes(bytes) that takes a number of bytes as input and converts it into a human-readable format (e.g., KB, MB, GB, etc.). This function is used to display the network usage in a more understandable format later in the script.
  • The monitor_network_usage() function is defined, which is the main part of the script responsible for monitoring the network usage.
  • Inside the monitor_network_usage() function, the variable old_value is initialized with the total number of bytes received and sent by the network interface using psutil.net_io_counters().bytes_recv and psutil.net_io_counters().bytes_sent. This value serves as the baseline for calculating the difference in network usage.
  • The variable total_bytes is initialized to keep track of the total data usage since the script started running.
  • The script enters a continuous loop using while True to monitor the network usage in real-time.
  • Within each iteration of the loop, the current value of bytes received and sent by the network interface is obtained using psutil.net_io_counters().bytes_recv and psutil.net_io_counters().bytes_sent, respectively, and stored in the variable new_value.
  • The difference between the new and old values of network usage is calculated and stored in the variable diff.
  • The old_value is updated to the new_value for the next iteration.
  • The diff value is added to total_bytes to keep track of the cumulative data usage.
  • The current network usage and total data usage are printed on the console using the print() function. The \r character at the beginning of the print statement ensures that each new print statement overwrites the previous one, providing a continuous display of network usage.
  • The script introduces a delay of 1 second using time.sleep(1) to wait before the next iteration of the loop.
  • The main body of the script is enclosed within the if __name__ == "__main__": condition, which ensures that the monitor_network_usage() function is executed only when the script is run directly and not imported as a module.
  • Finally, the monitor_network_usage() function is called to start monitoring the network usage.

Overall, this script continuously monitors the network usage and displays the real-time network usage in bytes per second and the total data usage since the script started running. 

Code 2:

The "Real-time Wi-Fi Data Usage Monitor" is a Python script that tracks and displays the data usage of a specific Wi-Fi network in real-time. It utilizes the psutil library to access system information and continuously retrieves the data usage of the specified Wi-Fi interface. The script provides a human-readable format for the data usage, updating the display every second. It offers a convenient way to monitor and keep track of the data consumption of a Wi-Fi network

  1. import psutil
  2. import time
  3. import datetime

  4. def convert_bytes(bytes):
  5. """
  6. Convert bytes to a human-readable format.
  7. """
  8. sizes = ["B", "KB", "MB", "GB", "TB"]
  9. i = 0
  10. while bytes >= 1024 and i < len(sizes)-1:
  11. bytes /= 1024
  12. i += 1
  13. return f"{bytes:.2f} {sizes[i]}"

  14. def get_wifi_data_usage(wifi_name, date):
  15. """
  16. Get data usage for a specific WiFi network and date.
  17. """
  18. data_usage = 0

  19. # Get network interfaces
  20. interfaces = psutil.net_io_counters(pernic=True)

  21. # Find the network interface for the specified WiFi name
  22. wifi_interface = None
  23. for interface, stats in interfaces.items():
  24. if wifi_name in interface:
  25. wifi_interface = interface
  26. break

  27. if wifi_interface is None:
  28. print(f"WiFi network '{wifi_name}' not found.")
  29. return

  30. while True:
  31. # Get the data usage for the specified WiFi interface and date
  32. network_io = psutil.net_io_counters(pernic=True)[wifi_interface]
  33. data_usage = network_io.bytes_recv + network_io.bytes_sent

  34. # Print the data usage without a newline character
  35. print(convert_bytes(data_usage), end='\r')

  36. # Wait for 1 second before updating the data usage
  37. time.sleep(1)

  38. if __name__ == "__main__":
  39. wifi_name = "Wi-Fi"
  40. today ="%Y-%m-%d")
  41. get_wifi_data_usage(wifi_name, today)

Post a Comment

If you have any doubts, please let me know

Previous Post Next Post