β‘ Python Power Shots β π₯οΈ System Monitor (CPU, RAM & Disk Stats)
Posted on: November 24, 2025
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!
No comments yet. Be the first to comment!