AW Dev Rethought

⚖️ There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies - C.A.R. Hoare

⚡ Python Power Shots – 🖥️ System Monitor (CPU, RAM & Disk Stats)


Description:

📌 Introduction

Want a quick system snapshot right from your terminal?

With the psutil library, Python can display real-time CPU usage, memory stats, and disk information — similar to Activity Monitor, Task Manager, or htop, but super lightweight.

This Power Shot helps you monitor your machine’s performance in seconds — perfect for debugging, system checks, or automation tools.


🔎 Explanation

  • psutil.cpu_percent() → returns CPU usage in percentage.
  • psutil.virtual_memory() → gives memory used, free, and available.
  • psutil.disk_usage() → reports disk space usage for any partition.
  • You can run this as a one-shot command or as a loop for continuous monitoring.

✅ Key Takeaways

  • 🖥️ Get real-time system stats from a single script.
  • ⚙️ Useful for debugging, monitoring, and dashboards.
  • 🧰 Powered by psutil — small, fast, and cross-platform.

Code Snippet:

# Import psutil for system monitoring
import psutil

# Import shutil to format bytes into readable units
import shutil

def format_bytes(size):
    """
    Convert bytes to human-readable units (KB, MB, GB).
    """
    return shutil._ntuple_diskusage((size, 0, 0)).total // (1024 ** 3)  # Quick conversion to GB

# --- Step 1: CPU Usage ---
cpu_usage = psutil.cpu_percent(interval=1)  # 1-second average
print(f"🧠 CPU Usage: {cpu_usage}%")

# --- Step 2: RAM Usage ---
memory = psutil.virtual_memory()
ram_total = memory.total / (1024 ** 3)
ram_used = memory.used / (1024 ** 3)
ram_percent = memory.percent

print(f"💾 RAM: {ram_used:.2f} GB / {ram_total:.2f} GB ({ram_percent}%)")

# --- Step 3: Disk Usage ---
disk = psutil.disk_usage('/')
disk_total = disk.total / (1024 ** 3)
disk_used = disk.used / (1024 ** 3)
disk_percent = disk.percent

print(f"📀 Disk: {disk_used:.2f} GB / {disk_total:.2f} GB ({disk_percent}%)")

# Optional: Display all partitions
# for part in psutil.disk_partitions():
#     print(part.device, psutil.disk_usage(part.mountpoint))

Link copied!

Comments

Add Your Comment

Comment Added!