Kill a Process by name using Python


Introduction

Processes are an essential component of managing system resources in the realm of programming. You might occasionally need to stop a process if it is acting erratically or using more resources than necessary. For these kinds of system-level activities, Python offers a great range of tools. In this post, we'll show you how to use Python to kill a process by name.

Python and System Processes

With its extensive libraries and modules, Python is a very flexible language that goes beyond straightforward scripting or web programming. Through libraries like os and psutil, you can interface with system-level features like process management.

Using the Psutil Library

The "process and system utilities" (psutil) library will be used to control system processes. It is a cross-platform library used to get process and system information. Using pip, you can install psutil if you don't already have it 

pip install psutil

Finding a Process by Name

A process must first be located before it can be terminated. Using psutil.process_iter() and psutil, we may find all instances of a process by name.Process.name() 

import psutil

def get_processes_by_name(name):
   """Return a list of processes matching 'name'."""
   matching_processes = [proc for proc in psutil.process_iter(['name']) if proc.info['name'] == name]
   return matching_processes

This function will return a list of process instances with the specified name.

Killing a Process by Name

We can now construct a function to stop these processes since we can discover them by name. We'll employ the kill() technique as we loop through the list of processes 

def kill_processes(processes):
   """Attempt to kill all 'processes'."""
   for proc in processes:
      try:
         proc.kill()
      except psutil.NoSuchProcess:
         print(f"No such process: {proc.pid}")
      except psutil.AccessDenied:
         print(f"Access denied to {proc.pid}")

We catch exceptions like NoSuchProcess and AccessDenied in this method that might be thrown after the process has ended.

Bringing It All Together

These operations can be used to write a script that ends all instances of a process −

import psutil

def get_processes_by_name(name):
   """Return a list of processes matching 'name'."""
   matching_processes = [proc for proc in psutil.process_iter(['name']) if proc.info['name'] == name]
   return matching_processes

def kill_processes(processes):
   """Attempt to kill all 'processes'."""
   for proc in processes:
      try:
         proc.kill()
      except psutil.NoSuchProcess:
         print(f"No such process: {proc.pid}")
      except psutil.AccessDenied:
         print(f"Access denied to {proc.pid}")

process_name = "process_to_kill"
processes_to_kill = get_processes_by_name(process_name)
kill_processes(processes_to_kill)

This script will find and kill all instances of process_to_kill.

Conclusion

Python's broad standard library and third-party modules enable efficient system interaction and process manipulation. We can easily manage system processes using the psutil library, including killing them by name. Because of this capacity, Python excels in system administration duties and scripts, further solidifying its reputation as a flexible and potent programming language.

Updated on: 17-Jul-2023

609 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements