Python Snippets

Real-time System Resource Monitor with Live Dashboard

This Python snippet creates a real-time system monitoring tool that displays CPU usage, memory consumption, and network statistics in a live-updating terminal dashboard. It’s useful for developers, system administrators, and anyone who wants to monitor their computer’s performance without relying on external tools.

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

class SystemMonitor:
    def __init__(self, max_history=60):
        """Initialize the system monitor with specified history length."""
        self.max_history = max_history
        self.cpu_history = deque(maxlen=max_history)
        self.memory_history = deque(maxlen=max_history)
        self.network_history = deque(maxlen=max_history)
        self.running = False
        self.lock = threading.Lock()
        
    def get_system_info(self):
        """Collect current system information."""
        # CPU information
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # Memory information
        memory = psutil.virtual_memory()
        
        # Network information
        net_io = psutil.net_io_sent()
        net_io_current = psutil.net_io_counters()
        
        return {
            'timestamp': datetime.now(),
            'cpu_percent': cpu_percent,
            'memory': {
                'total': memory.total,
                'available': memory.available,
                'used': memory.used,
                'percent': memory.percent
            },
            'network': {
                'bytes_sent': net_io_current.bytes_sent,
                'bytes_recv': net_io_current.bytes_recv,
                'packets_sent': net_io_current.packets_sent,
                'packets_recv': net_io_current.packets_recv
            }
        }
    
    def update_stats(self):
        """Update system statistics in a separate thread."""
        while self.running:
            info = self.get_system_info()
            with self.lock:
                self.cpu_history.append(info['cpu_percent'])
                self.memory_history.append(info['memory']['percent'])
                self.network_history.append(info['network'])
            time.sleep(1)
    
    def start_monitoring(self):
        """Start the monitoring process."""
        self.running = True
        self.monitor_thread = threading.Thread(target=self.update_stats)
        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 get_current_stats(self):
        """Get the latest system statistics."""
        with self.lock:
            if self.cpu_history and self.memory_history and self.network_history:
                latest_net = self.network_history[-1]
                prev_net = self.network_history[-2] if len(self.network_history) > 1 else latest_net
                
                # Calculate network speed (bytes/sec)
                if prev_net != latest_net:
                    time_diff = 1  # Approximate 1 second between samples
                    upload_speed = (latest_net['bytes_sent'] - prev_net['bytes_sent']) / time_diff
                    download_speed = (latest_net['bytes_recv'] - prev_net['bytes_recv']) / time_diff
                else:
                    upload_speed = download_speed = 0
                
                return {
                    'cpu_current': self.cpu_history[-1] if self.cpu_history else 0,
                    'memory_current': self.memory_history[-1] if self.memory_history else 0,
                    'cpu_average': sum(self.cpu_history) / len(self.cpu_history) if self.cpu_history else 0,
                    'memory_average': sum(self.memory_history) / len(self.memory_history) if self.memory_history else 0,
                    'upload_speed': upload_speed,
                    'download_speed': download_speed
                }
        return {}
    
    def render_dashboard(self):
        """Render the terminal dashboard."""
        stats = self.get_current_stats()
        if not stats:
            return "Collecting data..."
            
        # Clear screen (works on most terminals)
        print("\033[2J\033[H", end="")
        
        # Header
        print("=" * 60)
        print(f"  REAL-TIME SYSTEM MONITOR - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("=" * 60)
        
        # CPU Section
        cpu_current = stats['cpu_current']
        cpu_avg = stats['cpu_average']
        cpu_bar = "█" * int(cpu_current / 2) + "░" * (50 - int(cpu_current / 2))
        print(f"\nCPU USAGE:  [{cpu_bar}] {cpu_current:5.1f}% (Avg: {cpu_avg:5.1f}%)")
        
        # Memory Section
        mem_current = stats['memory_current']
        mem_avg = stats['memory_average']
        mem_bar = "█" * int(mem_current / 2) + "░" * (50 - int(mem_current / 2))
        print(f"MEMORY:     [{mem_bar}] {mem_current:5.1f}% (Avg: {mem_avg:5.1f}%)")
        
        # Network Section
        upload_speed = stats['upload_speed'] / 1024  # KB/s
        download_speed = stats['download_speed'] / 1024  # KB/s
        print(f"\nNETWORK:")
        print(f"  Upload:   {upload_speed:8.2f} KB/s")
        print(f"  Download: {download_speed:8.2f} KB/s")
        
        # Process Count
        process_count = len(psutil.pids())
        print(f"\nPROCESSES:  {process_count} running")
        
        # Help
        print("\n" + "-" * 60)
        print("Press Ctrl+C to exit")
        print("-" * 60)

def main():
    """Main function to run the system monitor."""
    monitor = SystemMonitor()
    
    try:
        monitor.start_monitoring()
        print("Starting system monitor... Please wait for data collection.")
        
        # Wait a bit to collect initial data
        time.sleep(2)
        
        while True:
            monitor.render_dashboard()
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n\nStopping monitor...")
        monitor.stop_monitoring()
        print("Monitor stopped. Goodbye!")

if __name__ == "__main__":
    main()

What This Code Does

This snippet creates a real-time system resource monitor that continuously tracks and displays:

The dashboard updates every second and provides a clean, visual representation of system performance directly in the terminal.

Why This Is Useful

  1. No External Dependencies: Unlike GUI-based monitors, this runs entirely in the terminal
  2. Real-time Monitoring: Updates every second with minimal system impact
  3. Visual Feedback: Progress bars provide immediate visual understanding of resource usage
  4. Historical Context: Shows average usage to identify trends
  5. Lightweight: Minimal overhead on system resources
  6. Portable: Works on Linux, macOS, and Windows

How to Run It

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

  3. Run the script:
    python system_monitor.py
    
  4. To exit, press Ctrl+C

The monitor will start collecting data immediately and display a live dashboard in your terminal. The first few seconds will show “Collecting data…” as it gathers initial statistics. After that, you’ll see real-time updates of your system’s performance.

The visual bars for CPU and memory provide an intuitive way to see resource utilization at a glance, with each full block representing 2% usage. Network speeds show current upload/download rates, and the process count helps identify system load.