Summary
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:
- import psutil
- import time
- def convert_bytes(bytes):
- """
- Convert bytes to a human-readable format.
- """
- sizes = ["B", "KB", "MB", "GB", "TB"]
- i = 0
- while bytes >= 1024 and i < len(sizes)-1:
- bytes /= 1024
- i += 1
- return f"{bytes:.2f} {sizes[i]}"
- def monitor_network_usage():
- """
- Monitor network usage in real-time.
- """
- old_value = psutil.net_io_counters().bytes_recv + psutil.net_io_counters().bytes_sent
- total_bytes = 0
- while True:
- new_value = psutil.net_io_counters().bytes_recv + psutil.net_io_counters().bytes_sent
- diff = new_value - old_value
- old_value = new_value
- total_bytes += diff
- print(f"\rNetwork Usage: {convert_bytes(diff)}/s | Total Data Usage: {convert_bytes(total_bytes)}", end="")
- time.sleep(1)
- if __name__ == "__main__":
- 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
- import psutil
- import time
- import datetime
- def convert_bytes(bytes):
- """
- Convert bytes to a human-readable format.
- """
- sizes = ["B", "KB", "MB", "GB", "TB"]
- i = 0
- while bytes >= 1024 and i < len(sizes)-1:
- bytes /= 1024
- i += 1
- return f"{bytes:.2f} {sizes[i]}"
- def get_wifi_data_usage(wifi_name, date):
- """
- Get data usage for a specific WiFi network and date.
- """
- data_usage = 0
- # Get network interfaces
- interfaces = psutil.net_io_counters(pernic=True)
- # Find the network interface for the specified WiFi name
- wifi_interface = None
- for interface, stats in interfaces.items():
- if wifi_name in interface:
- wifi_interface = interface
- break
- if wifi_interface is None:
- print(f"WiFi network '{wifi_name}' not found.")
- return
- while True:
- # Get the data usage for the specified WiFi interface and date
- network_io = psutil.net_io_counters(pernic=True)[wifi_interface]
- data_usage = network_io.bytes_recv + network_io.bytes_sent
- # Print the data usage without a newline character
- print(convert_bytes(data_usage), end='\r')
- # Wait for 1 second before updating the data usage
- time.sleep(1)
- if __name__ == "__main__":
- wifi_name = "Wi-Fi"
- today = datetime.date.today().strftime("%Y-%m-%d")
- get_wifi_data_usage(wifi_name, today)