How to Create a List of Running Processes using Python

I will walk you through an exciting Python project that helps manage system processes efficiently. Using the psutil library, we will retrieve, filter, and manipulate system processes, all within a user-friendly interactive menu.

Why Monitor System Processes?

System monitoring is essential for developers, IT administrators, and power users who want to:

  • Keep track of running processes
  • Identify high CPU or memory usage
  • Kill unnecessary processes
  • Filter and save process details for analysis

Getting Started: Importing psutil

The psutil module is a cross-platform library that provides various utilities to manage system resources, including CPU, memory, disk, network, and running processes. First, ensure you have it installed:

pip install psutil

Then, import it in your Python script:

import psutil

Listing All Running Processes

We start by retrieving a list of all running processes and displaying key details such as Process ID (PID), Name, Status, and Username.

print(f"{'PID':<10} {'Name':<25} {'Status':<15} {'Username':<20}")
print("-" * 70)

for proc in psutil.process_iter(['pid', 'name', 'status', 'username']):
    try:
        pid = proc.info['pid']
        name = proc.info['name'] or "N/A"
        status = proc.info['status'] or "N/A"
        username = proc.info['username'] or "N/A"

        print(f"{pid:<10} {name:<25} {status:<15} {username:<20}")
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        pass

How It Works

  1. Printing the header: The script prints column headers with proper formatting.
  2. Iterating through processes: The psutil.process_iter() function retrieves all running processes with specified attributes.
  3. Handling missing data: If an attribute is missing, it defaults to “N/A.”
  4. Exception handling: If a process no longer exists or is inaccessible, it is skipped.

Adding Practical Functionalities

Now, let’s make the script more useful by: Sorting processes by PID, Filtering processes by name, Displaying CPU and memory usage, Saving the process list to a file.

Here’s the improved version of our script:

import psutil

def list_processes(filter_name=None):
    print(f"{'PID':<10} {'Name':<25} {'Status':<15} {'Username':<20} {'CPU%':<10} {'Memory%':<10}")
    print("-" * 90)
    
    processes = []
    
    for proc in psutil.process_iter(['pid', 'name', 'status', 'username', 'cpu_percent', 'memory_percent']):
        try:
            pid = proc.info['pid']
            name = proc.info['name'] or "N/A"
            status = proc.info['status'] or "N/A"
            username = proc.info['username'] or "N/A"
            cpu = proc.info['cpu_percent'] or 0.0
            memory = proc.info['memory_percent'] or 0.0

            if filter_name and filter_name.lower() not in name.lower():
                continue

            processes.append((pid, name, status, username, cpu, memory))

        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pass
    
    processes.sort(key=lambda x: x[0])
    
    for pid, name, status, username, cpu, memory in processes:
        print(f"{pid:<10} {name:<25} {status:<15} {username:<20} {cpu:<10.2f} {memory:<10.2f}")
    
    return processes

def terminate_process(pid):
    try:
        process = psutil.Process(pid)
        process.terminate()
        print(f"Process {pid} terminated successfully.")
    except psutil.NoSuchProcess:
        print(f"Process {pid} not found.")
    except psutil.AccessDenied:
        print(f"Permission denied: Cannot terminate process {pid}.")

while True:
    print("\nProcess Manager")
    print("1. List all processes")
    print("2. Filter processes by name")
    print("3. Terminate a process by PID")
    print("4. Exit")
    
    choice = input("Enter your choice: ")
    
    if choice == '1':
        process_list = list_processes()
    elif choice == '2':
        name_filter = input("Enter process name to filter: ")
        process_list = list_processes(filter_name=name_filter)
    elif choice == '3':
        pid_to_terminate = int(input("Enter PID to terminate: "))
        terminate_process(pid_to_terminate)
    elif choice == '4':
        break
    else:
        print("Invalid choice. Please try again.")

New Functionalities Added

  • Sorting: The process list is sorted by PID before displaying.
  • Filtering: Users can filter processes by name (e.g., entering ‘chrome’ shows only Chrome-related processes).
  • CPU and Memory Usage: Displays resource consumption per process.
  • Terminate a Process: Users can kill a process by entering its PID.
  • Interactive Menu: Provides a more user-friendly experience.

Final Thoughts

With this script, managing system processes becomes easier and more efficient. Whether you’re monitoring CPU/memory usage or terminating unnecessary tasks, this Python project serves as a powerful utility for system administration.

Related blog posts