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
How to Terminate a Running Process on Windows in Python?
When working with Python on Windows, you may need to terminate running processes due to unresponsiveness, high resource usage, or to stop script execution. Python provides several methods to accomplish this task using the os module, psutil library, and subprocess module.
Using the os Module
The os module allows you to execute operating system commands. On Windows, you can use the taskkill command to terminate processes ?
import os
# The process name to terminate
process_name = "notepad.exe"
# Using taskkill command to terminate the process
result = os.system(f"taskkill /f /im {process_name}")
if result == 0:
print(f"Process terminated successfully: {process_name}")
else:
print("Error occurred while terminating the process.")
SUCCESS: The process "notepad.exe" with PID 1234 has been terminated. Process terminated successfully: notepad.exe
This code uses the taskkill command with /f (force) and /im (image name) flags to forcefully terminate the specified process.
Using the psutil Library
The psutil library provides a powerful, cross-platform solution for system information and process manipulation. First, install it using ?
pip install psutil
Here's how to terminate a process using psutil ?
import psutil
# The process name to terminate
process_name = "notepad.exe"
# Iterate through all running processes
for proc in psutil.process_iter(['pid', 'name']):
try:
# Check if process name matches target process
if proc.info['name'] == process_name:
# Terminate the process
proc.terminate()
print(f"Process terminated: PID {proc.info['pid']}, Name: {proc.info['name']}")
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
# Handle exceptions during process information retrieval
pass
Process terminated: PID 5678, Name: notepad.exe
This method iterates through all running processes using psutil.process_iter() and terminates matching processes using the terminate() method.
Using the subprocess Module
The subprocess module allows you to spawn new processes and execute commands. You can use it to run the taskkill command ?
import subprocess
# The process name to terminate
process_name = "notepad.exe"
# Using subprocess to execute taskkill command
result = subprocess.run(f"taskkill /f /im {process_name}",
shell=True, capture_output=True, text=True)
if result.returncode == 0:
print(f"Process terminated successfully: {process_name}")
print(result.stdout.strip())
else:
print("Error occurred while terminating the process.")
print(result.stderr.strip())
Process terminated successfully: notepad.exe SUCCESS: The process "notepad.exe" with PID 9012 has been terminated.
This example uses subprocess.run() to execute the taskkill command with capture_output=True to capture the command output.
Terminating by Process ID
You can also terminate a process by its Process ID (PID) instead of name ?
import psutil
# Terminate process by PID
pid = 1234 # Replace with actual PID
try:
process = psutil.Process(pid)
process.terminate()
print(f"Process with PID {pid} terminated successfully.")
except psutil.NoSuchProcess:
print(f"No process found with PID {pid}")
except psutil.AccessDenied:
print(f"Access denied to terminate process with PID {pid}")
Process with PID 1234 terminated successfully.
Comparison
| Method | Cross-Platform | Error Handling | Best For |
|---|---|---|---|
os.system() |
No | Basic | Simple scripts |
psutil |
Yes | Excellent | Process monitoring |
subprocess |
No | Good | Command execution |
Conclusion
Python offers multiple ways to terminate processes on Windows. Use psutil for robust, cross-platform process management with excellent error handling. For simple tasks, os.system() or subprocess work well but are Windows-specific when using taskkill.
