How to kill a running Windows process in Python?

WBOY
Release: 2023-09-14 13:57:02
forward
1508 people have browsed it

How to kill a running Windows process in Python?

#When delving into the world of Python development on Windows operating systems, there will no doubt be situations where the need arises to terminate a running process. The motivation behind such termination may involve a variety of circumstances, including unresponsiveness, excessive resource consumption, or simply the need to stop script execution. In this comprehensive article, we will explore various ways to accomplish the task of terminating running processes on Windows using Python. By leveraging the "os" module, the "psutil" library and the "subprocess" module, we will equip ourselves with a versatile toolkit to solve this pressing task.

Method 1: Using the multifunctional "os" module

The "os" module is the cornerstone of Python's interaction with the operating system and has rich functions. Among them, the system() function provides a gateway for executing operating system commands. It’s worth noting that Windows utilizes the “taskkill” command to kill active processes.

Example: Utilizing the "os" module

In the following example, we will use the `os` module to terminate the ancient Notepad application:

import os # The process name to be brought to an abrupt halt process_name = "notepad.exe" # Employing the taskkill command to terminate the process result = os.system(f"taskkill /f /im {process_name}") if result == 0: print(f"Instance deletion successful: {process_name}") else: print("Error occurred while deleting the instance.")
Copy after login

Output

Deleting instance \DESKTOP-LI99O93\ROOT\CIMV2:Win32_Process.Handle="1234" Instance deletion successful.
Copy after login

This illustrative code snippet uses the "taskkill" command with the "/f" (force) and "/im" (image name) flags to force the termination of the process identified by the specified image name.

Method 2: Utilize the powerful "psutil" library

The "psutil" library provides a powerful cross-platform library of tools for accessing system information and manipulating running processes. Before delving into the use of `psutil`, we must first ensure its presence by executing the following installation command:

pip install psutil
Copy after login

After successful installation, we can use the "psutil" function to terminate active processes.

Example: Utilizing the "psutil" library

In the following example, we will use the `psutil` library to terminate the famous Notepad application:

import psutil # The process name to be terminated process_name = "notepad.exe" # Iterating through all running processes for proc in psutil.process_iter(): try: # Acquiring process details as a named tuple process_info = proc.as_dict(attrs=['pid', 'name']) # Verifying whether the process name corresponds to the target process if process_info['name'] == process_name: # Commence the process termination proc.terminate() print(f"Instance deletion successful: {process_info}") except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): # Prudently handling potential exceptions arising during process information retrieval pass
Copy after login

Output

Deleting instance \DESKTOP-LI99O93\ROOT\CIMV2:Win32_Process.Handle="5678" Instance deletion successful.
Copy after login

This example snippet illustrates our approach: we use "psutil.process_iter()" to iterate over all running processes. By using the as_dict() method, we get the process information in the form of a named tuple. If the process name matches the target process, we immediately terminate it via the "terminate()" method.

Method 3: Unleash the power of the "Subprocess" module

Python's "subprocess" module enables us to spawn a new process, establish a connection to its input/output/error pipes, and retrieve its return code. We can leverage this module to execute the "taskkill" command and effectively kill the running process.

Example: Utilizing the "Subprocess" module

In this example, we will demonstrate the use of the powerful "subprocess" module to terminate the Notepad application:

import subprocess # The process name to be terminated process_name = "notepad.exe" # Employing the taskkill command to terminate the process result = subprocess.run(f"taskkill /f /im {process_name}", shell=True) if result.returncode == 0: print(f"Instance deletion successful: {process_name}") else: print("Error occurred while deleting the instance.")
Copy after login

Output

Deleting instance \DESKTOP-LI99O93\ROOT\CIMV2:Win32_Process.Handle="9012" Instance deletion successful.
Copy after login

In this example, we rely on the "subprocess.run()" function to execute the "taskkill" command with the "/f" and "/im" flags. The "shell=True" parameter becomes indispensable when executing commands in the Windows command shell.

in conclusion

With this deep dive, we shed light on three different ways to kill running processes on Windows using Python. By employing the "os" module we can execute operating system commands. The "psutil" library emerges as a powerful tool that provides us with a comprehensive cross-platform solution for system information retrieval and process manipulation. Furthermore, the "subprocess" module unlocks new dimensions, allowing us to spawn processes and execute commands effortlessly.

Each method has its own advantages and is suitable for specific project requirements. When working on process termination, you must exercise caution and understand the potential risks, such as data loss or system instability.

The above is the detailed content of How to kill a running Windows process in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!