Python Snippets

Real-time System Resource Monitor with Visualization

This snippet creates a real-time system resource monitor that displays CPU usage, memory consumption, and network activity in a terminal dashboard. It’s particularly useful for developers, system administrators, and anyone who needs to keep track of their system’s performance without leaving the command line.

import psutil
import time
import threading
from datetime import datetime
from collections import deque
import os

class SystemMonitor:
    def __init__(self, max_points=50):
        self.max_points = max_points
        self.cpu_data = deque(maxlen=max_points)
        self.memory_data = deque(maxlen=max_points)
        self.network_data = deque(maxlen=max_points)
        self.timestamps = deque(maxlen=max_points)
        self.running = False
        self.lock = threading.Lock()
        
    def start_monitoring(self):
        """Start the monitoring process in a separate thread"""
        self.running = True
        self.monitor_thread = threading.Thread(target=self._collect_data)
        self.monitor_thread.daemon = True
        self.monitor_thread.start()
        
    def stop_monitoring(self):
        """Stop the monitoring process"""
        self.running = False
        if hasattr(self, 'monitor_thread'):
            self.monitor_thread.join()
            
    def _collect_data(self):
        """Collect system metrics in a loop"""
        # Get initial network counters
        net_io = psutil.net_io_bytes()
        prev_bytes_sent = net_io.bytes_sent
        prev_bytes_recv = net_io.bytes_recv
        
        while self.running:
            # Collect CPU and memory data
            cpu_percent = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            
            # Calculate network traffic (bytes per second)
            net_io = psutil.net_io_bytes()
            bytes_sent_per_sec = net_io.bytes_sent - prev_bytes_sent
            bytes_recv_per_sec = net_io.bytes_recv - prev_bytes_recv
            prev_bytes_sent = net_io.bytes_sent
            prev_bytes_recv = net_io.bytes_recv
            
            # Store data with thread safety
            with self.lock:
                timestamp = datetime.now()
                self.cpu_data.append(cpu_percent)
                self.memory_data.append(memory.percent)
                self.network_data.append((bytes_sent_per_sec, bytes_recv_per_sec))
                self.timestamps.append(timestamp)
                
            time.sleep(1)
    
    def _clear_screen(self):
        """Clear the terminal screen"""
        os.system('cls' if os.name == 'nt' else 'clear')
        
    def _draw_bar(self, value, max_value=100, width=30):
        """Draw a text-based bar chart"""
        filled = int(width * value / max_value)
        bar = '█' * filled + '░' * (width - filled)
        return f"[{bar}] {value:.1f}%"
    
    def _format_bytes(self, bytes_per_sec):
        """Format bytes per second to human readable format"""
        for unit in ['B/s', 'KB/s', 'MB/s', 'GB/s']:
            if bytes_per_sec < 1024.0:
                return f"{bytes_per_sec:.1f} {unit}"
            bytes_per_sec /= 1024.0
        return f"{bytes_per_sec:.1f} TB/s"
    
    def display(self):
        """Display the current system status"""
        self._clear_screen()
        
        # Get current system info
        cpu_percent = psutil.cpu_percent()
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        # Get network stats
        net_io = psutil.net_io_bytes()
        
        print("=" * 60)
        print(f"System Resource Monitor - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("=" * 60)
        
        # CPU Section
        print(f"\n🖥️  CPU Usage:")
        print(f"  {self._draw_bar(cpu_percent)}")
        
        # Memory Section
        print(f"\n💾 Memory Usage:")
        print(f"  {self._draw_bar(memory.percent)}")
        print(f"  Used: {memory.used / (1024**3):.1f} GB / {memory.total / (1024**3):.1f} GB")
        
        # Disk Section
        disk_percent = (disk.used / disk.total) * 100
        print(f"\n💿 Disk Usage:")
        print(f"  {self._draw_bar(disk_percent)}")
        print(f"  Used: {disk.used / (1024**3):.1f} GB / {disk.total / (1024**3):.1f} GB")
        
        # Network Section
        print(f"\n🌐 Network:")
        # Calculate average network activity from recent data
        with self.lock:
            if self.network_data:
                avg_sent = sum(data[0] for data in self.network_data) / len(self.network_data)
                avg_recv = sum(data[1] for data in self.network_data) / len(self.network_data)
                print(f"  Upload:   {self._format_bytes(avg_sent)}")
                print(f"  Download: {self._format_bytes(avg_recv)}")
            else:
                print("  Collecting data...")
        
        # Process Info
        processes = len(psutil.pids())
        print(f"\n📊 System Summary:")
        print(f"  Processes: {processes}")
        print(f"  Load Avg:  {', '.join(map(str, os.getloadavg())) if hasattr(os, 'getloadavg') else 'N/A'}")
        
        print("\n" + "=" * 60)
        print("Press Ctrl+C to exit")

def main():
    """Main function to run the system monitor"""
    monitor = SystemMonitor()
    
    try:
        monitor.start_monitoring()
        while True:
            monitor.display()
            time.sleep(2)  # Update display every 2 seconds
    except KeyboardInterrupt:
        print("\n\nStopping monitor...")
        monitor.stop_monitoring()
        print("Monitor stopped. Goodbye!")

if __name__ == "__main__":
    main()

What This Code Does

This system resource monitor provides a real-time view of your computer’s performance directly in the terminal. It tracks and visualizes:

  1. CPU Usage: Shows current processor utilization with a visual progress bar
  2. Memory Usage: Displays RAM consumption with used/total values
  3. Disk Usage: Shows storage space utilization on the root drive
  4. Network Activity: Monitors upload and download speeds in real-time
  5. System Summary: Provides process count and system load averages

The monitor updates every 2 seconds and runs until interrupted with Ctrl+C.

Why This Is Useful

How to Run It

  1. Install Dependencies:
    pip install psutil
    
  2. Save the code to a file (e.g., system_monitor.py)

  3. Run the script:
    python system_monitor.py
    
  4. Stop the monitor by pressing Ctrl+C

The monitor will display a continuously updating dashboard showing your system’s current resource usage. The network section shows average traffic over time for more stable readings, and all values are automatically formatted for human readability (GB, MB, KB units).