Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Build a Terminal Dashboard That Displays Real-Time System Performance in Python

A Python script that reads Linux system files to display a real-time terminal dashboard with CPU usage, memory usage, and CPU temperature.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Python code

61 lines
Python 3.9+
import os, time, sys
from collections import deque

def get_cpu_temp():
    try:
        with open("/sys/class/thermal/thermal_zone0/temp") as f:
            return round(int(f.read().strip()) / 1000, 1)
    except:
        return None

def get_mem_usage():
    with open("/proc/meminfo") as f:
        lines = f.readlines()
        total = int(lines[0].split()[1])
        free = int(lines[1].split()[1])
        buffers = int(lines[3].split()[1])
        cached = int(lines[4].split()[1])
        used = total - free - buffers - cached
        return used, total

def get_cpu_usage(history):
    with open("/proc/stat") as f:
        cpu_line = f.readline().split()
        idle = int(cpu_line[4])
        total = sum(int(v) for v in cpu_line[1:])
    if history:
        prev_idle, prev_total = history[-1]
        delta_idle = idle - prev_idle
        delta_total = total - prev_total
        usage = 100.0 * (1 - delta_idle / delta_total) if delta_total else 0
    else:
        usage = 0
    history.append((idle, total))
    return usage

def draw_dashboard(cpu_pct, mem_used, mem_total, cpu_temp, bar_width=30):
    os.system('clear')
    mem_pct = int(100 * mem_used / mem_total)
    used_bar = '█' * int(mem_pct * bar_width / 100)
    free_bar = '░' * (bar_width - len(used_bar))
    cpu_bar = '█' * int(cpu_pct * bar_width / 100)
    cpu_empty = '░' * (bar_width - len(cpu_bar))
    temp_str = f"{cpu_temp}°C" if cpu_temp is not None else "N/A"
    print(f"CPU: [{cpu_bar}{cpu_empty}] {cpu_pct:.1f}%  Temp: {temp_str}")
    print(f"MEM: [{used_bar}{free_bar}] {mem_pct}% ({mem_used//1024}MB / {mem_total//1024}MB)")
    print(f"Time: {time.strftime('%H:%M:%S')}")

def main():
    cpu_history = deque(maxlen=2)
    try:
        while True:
            cpu_pct = get_cpu_usage(cpu_history)
            mem_used, mem_total = get_mem_usage()
            cpu_temp = get_cpu_temp()
            draw_dashboard(cpu_pct, mem_used, mem_total, cpu_temp)
            time.sleep(2)
    except KeyboardInterrupt:
        print("\nDashboard closed.")

if __name__ == "__main__":
    main()

Output

stdout
CPU: [██████████████████████████████] 45.2%  Temp: 68.0°C
MEM: [████████████████████░░░░░░░░░░] 65% (3215MB / 4904MB)
Time: 14:30:22

How it works

The dashboard reads from the /proc and /sys virtual filesystems on Linux to get live system metrics. get_cpu_usage() calculates the CPU usage percentage by comparing idle and total CPU time between two samples, stored in a deque with a max length of 2. get_mem_usage() parses /proc/meminfo to compute used memory excluding buffers and cache. The terminal is cleared each cycle using os.system('clear') to refresh the display. A KeyboardInterrupt handler gracefully stops the loop.

Common mistakes

  • Assuming this script works on Windows or macOS without modification (it only works on Linux).
  • Not handling the case where `/sys/class/thermal/thermal_zone0/temp` does not exist, causing an exception.
  • Calculating memory usage incorrectly by not excluding buffers and cache from the used memory.
  • Using a long sleep interval that makes the dashboard feel unresponsive.

Variations

  1. Use `psutil` library for cross-platform system monitoring without reading Linux-specific files.
  2. Add network I/O or disk usage by parsing additional files like `/proc/net/dev` or `/proc/diskstats`.
  3. Implement a scrolling line graph of CPU usage over time using characters like `▁▂▃▄▅▆▇█`.

Real-world use cases

  • A DevOps engineer monitors server resource usage in a terminal while debugging a performance issue.
  • A developer embeds a lightweight dashboard in a CLI tool for real-time feedback during long-running tasks.
  • A Raspberry Pi project displays CPU temperature and memory in a headless setup without a desktop environment.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.