How to Detect Applications Consuming Excessive Memory in Python
Use psutil to list the top memory-using processes by RSS and print their names, PIDs, and memory usage in MB.
pip install psutil
Python code
22 linesimport psutil
def find_top_memory_processes(limit=5):
"""Return top `limit` processes by memory usage (RSS)."""
processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
try:
info = proc.info
mem = info['memory_info'].rss if info['memory_info'] else 0
processes.append((info['name'], info['pid'], mem))
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
processes.sort(key=lambda x: x[2], reverse=True)
return processes[:limit]
if __name__ == "__main__":
print("Top memory-consuming processes:")
for name, pid, rss in find_top_memory_processes():
mb = rss / (1024 * 1024)
print(f" {name:<25} PID {pid:<6} {mb:.1f} MB")
Output
Top memory-consuming processes:
python3 PID 1234 256.3 MB
chrome PID 5678 512.7 MB
slack PID 9012 128.4 MB
code PID 3456 345.2 MB
firefox PID 7890 200.1 MB
How it works
The script iterates over all running processes using psutil.process_iter with specific attributes to minimise overhead. For each process, it extracts the Resident Set Size (RSS) from memory_info and stores the process name, PID, and memory. Exceptions like NoSuchProcess and AccessDenied are caught so the loop continues without crashing. Once collected, the list is sorted descending by memory and the top N processes are returned. The MB conversion and formatted print make the output human-readable.
Common mistakes
- Not catching `psutil.AccessDenied` which crashes the script on protected processes.
- Forgetting to convert RSS bytes to MB, showing huge raw numbers.
- Using `psutil.process_iter()` without attributes, which fetches all info and slows execution.
Variations
- Sort by CPU percent instead of memory to find CPU-intensive processes.
- Use `psutil.virtual_memory().percent` to check overall system memory pressure.
Real-world use cases
- Automated monitoring script that logs when any single process exceeds a memory threshold on a production server.
- CI pipeline step that checks for memory leaks by comparing top memory processes before and after integration tests.
- System admin tool that periodically alerts via email if a known application (e.g., Chrome) uses more than a set limit.
Sponsored
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.