Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Kill a Process by name using Python
Processes are an essential component of managing system resources in programming. You might occasionally need to stop a process if it is acting erratically or consuming excessive resources. Python offers excellent tools for these system-level activities through libraries like psutil. In this article, we'll show you how to use Python to kill a process by name.
Installing Psutil
The psutil (process and system utilities) library is a cross-platform library used to retrieve process and system information. Install it using pip if you don't already have it ?
pip install psutil
Finding a Process by Name
Before terminating a process, we must first locate it. Using psutil.process_iter(), we can find all instances of a process by name ?
import psutil
def get_processes_by_name(name):
"""Return a list of processes matching 'name'."""
matching_processes = []
for proc in psutil.process_iter(['name']):
if proc.info['name'] == name:
matching_processes.append(proc)
return matching_processes
# Example usage
processes = get_processes_by_name('notepad.exe')
print(f"Found {len(processes)} process(es)")
This function returns a list of process instances with the specified name.
Killing a Process by Name
Now we can construct a function to terminate these processes. We'll use the kill() method while handling potential exceptions ?
import psutil
def kill_processes_by_name(process_name):
"""Kill all processes with the given name."""
killed_count = 0
for proc in psutil.process_iter(['name']):
if proc.info['name'] == process_name:
try:
proc.kill()
print(f"Killed process: {proc.pid}")
killed_count += 1
except psutil.NoSuchProcess:
print(f"Process {proc.pid} already terminated")
except psutil.AccessDenied:
print(f"Access denied to kill process {proc.pid}")
except Exception as e:
print(f"Error killing process {proc.pid}: {e}")
return killed_count
# Example usage
count = kill_processes_by_name('notepad.exe')
print(f"Total processes killed: {count}")
We handle exceptions like NoSuchProcess and AccessDenied that might be thrown if the process has already ended or lacks permissions.
Complete Example
Here's a comprehensive script that demonstrates finding and killing processes by name ?
import psutil
import time
def list_processes_by_name(process_name):
"""List all processes with the given name."""
processes = []
for proc in psutil.process_iter(['pid', 'name', 'status']):
if proc.info['name'] == process_name:
processes.append(proc.info)
return processes
def kill_processes_by_name(process_name):
"""Kill all processes with the given name."""
killed_count = 0
for proc in psutil.process_iter(['name']):
if proc.info['name'] == process_name:
try:
proc.kill()
killed_count += 1
print(f"Killed process: PID {proc.pid}")
except psutil.NoSuchProcess:
print(f"Process PID {proc.pid} no longer exists")
except psutil.AccessDenied:
print(f"Access denied for process PID {proc.pid}")
except Exception as e:
print(f"Error: {e}")
return killed_count
# Example usage
process_name = "python.exe"
# List processes before killing
print("Processes before killing:")
processes = list_processes_by_name(process_name)
for proc in processes:
print(f"PID: {proc['pid']}, Status: {proc['status']}")
print(f"\nAttempting to kill all '{process_name}' processes...")
killed = kill_processes_by_name(process_name)
print(f"Successfully killed {killed} process(es)")
Important Considerations
When killing processes, consider these important points:
- Permissions: You may need administrator privileges to kill certain processes
- Critical processes: Avoid killing system-critical processes as it may crash your system
-
Graceful termination: Use
terminate()instead ofkill()for gentler process termination - Process verification: Always verify the process before killing to avoid accidents
Using terminate() vs kill()
Python's psutil provides two methods for stopping processes ?
import psutil
def graceful_kill(process_name, timeout=5):
"""Attempt graceful termination before force killing."""
for proc in psutil.process_iter(['name']):
if proc.info['name'] == process_name:
try:
# First try graceful termination
proc.terminate()
proc.wait(timeout=timeout)
print(f"Gracefully terminated process {proc.pid}")
except psutil.TimeoutExpired:
# Force kill if timeout expires
proc.kill()
print(f"Force killed process {proc.pid}")
except Exception as e:
print(f"Error: {e}")
# Example usage
graceful_kill("notepad.exe")
Conclusion
Python's psutil library provides powerful tools for system process management, including the ability to find and terminate processes by name. Always handle exceptions properly and consider using graceful termination before force killing processes.
