Building a Custom Process Killer in Python: A Step-by-Step Guide

Written by

in

Building a custom process killer in Python allows you to automate the termination of unresponsive applications, manage system resources, or create custom task managers.

Here is a step-by-step guide to building one using the powerful psutil library. ⚙️ Prerequisites

You need the psutil cross-platform library to interact with system processes. Install it via your terminal: pip install psutil Use code with caution. 🛠️ Step 1: Import Modules and Find a Process

To kill a process, you first need to locate it by its name (e.g., “chrome.exe” or “python”).

import psutil def find_procs_by_name(name): “”“Return a list of processes matching the given name.”“” ls = [] for p in psutil.process_iter([‘pid’, ‘name’]): if name.lower() in p.info[‘name’].lower(): ls.append(p) return ls Use code with caution. ❌ Step 2: Terminate the Process Safely

Once found, you should attempt a graceful termination (terminate()). If the process refuses to close, force-kill it (kill()).

def kill_process_by_name(process_name): processes = find_procs_by_name(process_name) if not processes: print(f”No active process found matching: {process_name}“) return for proc in processes: try: print(f”Terminating {proc.info[‘name’]} (PID: {proc.info[‘pid’]})…“) proc.terminate() # Graceful shutdown # Wait up to 3 seconds for it to exit proc.wait(timeout=3) print(“Process terminated successfully.”) except psutil.TimeoutExpired: print(“Timed out. Forcing kill…”) proc.kill() # Forced shutdown except (psutil.NoSuchProcess, psutil.AccessDenied) as e: print(f”Error handling process: {e}“) Use code with caution. 📊 Step 3: Filter by Resource Usage (Advanced)

A smart process killer targets apps consuming too much memory or CPU.

def kill_high_memory_processes(threshold_mb): “”“Kills any process exceeding a specific memory threshold.”“” for proc in psutil.process_iter([‘pid’, ‘name’, ‘memory_info’]): try: # Convert bytes to Megabytes mem_usage = proc.info[‘memory_info’].rss / (10241024) if mem_usage > threshold_mb: print(f”{proc.info[‘name’]} is using {mem_usage:.2f}MB. Killing…“) proc.kill() except (psutil.NoSuchProcess, psutil.AccessDenied): continue Use code with caution. ⚠️ Critical Considerations

Permissions: Windows users may need to run the script as Administrator. Linux/macOS users may need sudo.

System Stability: Avoid killing vital system processes (like systemd, svchost.exe, or explorer.exe).

Zombies: Use proc.wait() to ensure the operating system cleans up the process entry properly.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *