The user wants a Python script to monitor and visualize system network traffic.
1. Understand the Goal:
Monitor: Read network usage data (bytes sent/received) from the operating system.
Visualize: Display this data in a graph (real-time or near real-time).
Language: Python.
2. Choose the Right Tools (Libraries):
Monitoring:psutil is the industry standard for system monitoring in Python. It's cross-platform (Windows, Linux, macOS). Specifically, psutil.net_io_counters() is the function needed.
Visualization:matplotlib is the standard plotting library. Its animation module is perfect for real-time updating.
3. Design the Logic:
Data Collection:
Need to sample network usage at intervals (e.g., every 1 second).
psutil gives cumulative totals (total bytes sent/received since boot).
To get speed (throughput, e.g., Mbps), I need to calculate the difference between the current sample and the previous sample, divided by the time elapsed.
Data Storage:
Lists are sufficient for a simple script.
Store X-axis (time) and Y-axis (upload/download speed).
Need a rolling window (e.g., last 60 seconds) so the chart doesn't become unreadable.
Visualization:
Set up a Figure and Axes.
Plot two lines: Upload and Download.
Use FuncAnimation to update the plot periodically.
Add labels, legends, and auto-scaling axes.
4. Step-by-Step Implementation Plan:
Prerequisites: Install psutil and matplotlib.
Step 1: Import Libraries.
Step 2: Define Helper Functions.
Function to get current bytes.
Function to convert bytes to human-readable format (Mbps or KBps) to make the graph useful.
Step 3: Setup the Animation Loop.
Initialize lists for data.
Define the update function:
Get current stats.
Calculate speed.
Append to lists.
Keep lists trimmed (rolling window).
Update plot data.
Step 4: Final Polish.
Add a main block.
Handle errors (optional but good).
5. Refining the Code (Self-Correction during drafting):
Issue:psutil returns bytes. A graph in "Bytes per second" is often large and hard to read.
Fix: Convert to Megabits per second (Mbps) since that's standard for network speeds, or keep it flexible. Let's stick to Megabits/second (Mbps) or Kilobytes/second depending on scale, but for simplicity in a script, Megabits (dividing by 1,000,000) or Megabytes (dividing by 1,048,576) is common. Let's use Mbps (divide by 1024*1024 bits? No, usually network speed is bits).
Let's provide a toggle or just stick to a standard. Let's do MB/s (Megabytes per second) for user intuition (file sizes) or Mbps. Let's stick to Megabytes per second (MB/s) because it feels more natural when looking at a graph of system usage, but standard network tools usually use Mbps. Let's do Mbps for the "network" feel.
Actually, for a simple monitor, usually people want to know how fast a file is downloading. Let's do Download/Upload Speed (Mbps). Formula: (bytes_diff * 8) / (1024 * 1024).
Wait, simpler is better. Let's just plot "Speed" and auto-format the Y-axis or keep it simple. Let's just use Megabits per second (Mbps) as the unit.
Issue: The X-axis. What should it be?
Fix: Time relative to start (0s, 1s, 2s...) or just keep a rolling window of integers.
Visuals: Two lines (Upload, Download). Different colors (e.g., Red for Upload, Green for Download).
6. Writing the Code (Mental Draft):
python
import psutil
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Config
interval = 1 # second
# Data
x_vals = []
y_down = []
y_up = []
def get_speed():
# call psutil
# calculate diff
pass
def animate(i):
# update data
# update plot
pass
7. Adding Robustness:
Initial values check. The first time animate runs, there's no "previous" value to subtract. Handle None.
Rolling Window: If the list exceeds 60 items (60 seconds), remove the first one.
Let's write the actual code now.
python
import time
import psutil
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# ... logic ...
I will generate the code with comments explaining the logic. I will use a class-based approach or global variables? Global variables are easier for a simple script, but a Class is cleaner. Let's stick to a clean functional approach with global lists for simplicity, as it's easier for a beginner to read.
Wait, psutil.net_io_counters() returns sent and received. "Sent" is Upload, "Received" is Download.
Calculation:
curr_sent, curr_recv = current stats
prev_sent, prev_recv = previous stats
upload_speed = (curr_sent - prev_sent) / time_elapseddownload_speed = (curr_recv - prev_recv) / time_elapsed
Let's implement.
To build this script, we will use psutil to retrieve system network data (bytes sent/received) and matplotlib to create a real-time visualization graph.
Prerequisites
You will need to install the following libraries via your terminal/command prompt:
bash
pip install psutil matplotlib
The Python Script
Save the following code as network_monitor.py.
This script calculates the speed (throughput) by comparing the current total bytes with the bytes from one second ago. It then updates the graph in real-time.
python
import time
import psutil
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# --- Configuration ---
UPDATE_INTERVAL = 1.0 # Seconds between updates
MAX_POINTS = 60 # Number of data points to show on the graph (e.g., last 60 seconds)
# --- Data Storage ---
# We use lists to store the time and speed data
times = []
download_speeds = []
upload_speeds = []
# Variables to store the previous state of network counters
prev_net_io = psutil.net_io_counters()
prev_time = time.time()
def convert_to_mb(bytes_per_sec):
"""Converts bytes per second to Megabits per second (Mbps).
Note: 1 Byte = 8 bits. Standard network speed is usually measured in bits."""
return (bytes_per_sec * 8) / (1024 * 1024)
def update_graph(frame):
"""Function called by FuncAnimation to update data and redraw the plot."""
global prev_net_io, prev_time
# 1. Get current data
curr_net_io = psutil.net_io_counters()
curr_time = time.time()
# 2. Calculate time difference
time_elapsed = curr_time - prev_time
# 3. Calculate bytes transferred since last check
bytes_sent_delta = curr_net_io.bytes_sent - prev_net_io.bytes_sent
bytes_recv_delta = curr_net_io.bytes_recv - prev_net_io.bytes_recv
# 4. Calculate speed (Bytes per second)
upload_speed_bps = bytes_sent_delta / time_elapsed
download_speed_bps = bytes_recv_delta / time_elapsed
# 5. Convert to Mbps for readability
upload_speed_mbps = convert_to_mb(upload_speed_bps)
download_speed_mbps = convert_to_mb(download_speed_bps)
# 6. Update previous state for next calculation
prev_net_io = curr_net_io
prev_time = curr_time
# 7. Store data in lists
times.append(curr_time)
download_speeds.append(download_speed_mbps)
upload_speeds.append(upload_speed_mbps)
# 8. Limit lists to MAX_POINTS to keep graph clean (Rolling Window)
if len(times) > MAX_POINTS:
times.pop(0)
download_speeds.pop(0)
upload_speeds.pop(0)
# 9. Clear axis and plot new data
plt.cla()
# Plot Download (Blue) and Upload (Red)
plt.plot(times, download_speeds, label="Download (Mbps)", color="blue", linewidth=2)
plt.plot(times, upload_speeds, label="Upload (Mbps)", color="red", linewidth=2)
# Formatting the Graph
plt.title("Real-Time Network Traffic")
plt.xlabel("Time")
plt.ylabel("Speed (Mbps)")
plt.legend(loc="upper right")
plt.grid(True, linestyle='--', alpha=0.7)
# Auto-format the time axis to look nice
plt.gcf().autofmt_xdate()
def main():
print("Starting Network Monitor...")
print(f"Updating every {UPDATE_INTERVAL} second(s). Close the window to stop.")
# Create the figure
plt.figure(figsize=(10, 6))
# Create the animation
# 'interval' is in milliseconds, so we multiply seconds by 1000
ani = FuncAnimation(plt.gcf(), update_graph, interval=int(UPDATE_INTERVAL * 1000))
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
How it Works
Data Retrieval (psutil):
psutil.net_io_counters() returns the total number of bytes sent and received since the computer booted up.
Because this number only goes up, we cannot plot it directly. We have to calculate the difference between the current reading and the reading from 1 second ago to find the speed.
Calculating Speed:
Delta Bytes / Delta Time = Speed (Bytes/sec)
The script converts this into Mbps (Megabits per second), which is the standard unit for internet speed (Multiplying bytes by 8 to get bits).
Visualization (matplotlib):
We use FuncAnimation. This runs the update_graph function every second (1000ms).
We maintain a "Rolling Window" (defined by MAX_POINTS). If you set it to 60, the graph will only show the last 60 seconds of activity, preventing the chart from becoming too crowded.
How to Run It
Open your terminal or command prompt.
Run the script:
bash
python network_monitor.py
A window will appear. Try downloading a file or running a speed test in your browser, and you will see the blue "Download" line spike up in real-time.