search
HomeBackend DevelopmentPython TutorialHow to kill a running Windows process in Python?

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.")

Output

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

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

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

Output

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

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.")

Output

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

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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!