Maintenance

Site is under maintenance — quizzes are still available.

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

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.

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

Requires third-party packages — install first
pip install psutil

Python code

22 lines
Python 3.6+
import 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

stdout
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

  1. Sort by CPU percent instead of memory to find CPU-intensive processes.
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.