📌  相关文章
📜  如何在Python中终止 Windows 上正在运行的进程?

📅  最后修改于: 2022-05-13 01:54:37.804000             🧑  作者: Mango

如何在Python中终止 Windows 上正在运行的进程?

进程是正在执行(处理)的程序。进程可能不必由用户显式运行,它可以是操作系统产生的系统进程。任何在操作系统上执行的应用程序首先创建一个自己的进程来执行。在典型的操作系统安装中,大多数进程是操作系统服务和后台应用程序,它们运行以维护操作系统、软件和硬件。在本文中,我们将了解通过Python终止 Windows 操作系统上正在运行的进程的不同方法。首先,我们将描述一种实现结果的Python方法,然后查看在 Windows 命令处理器中找到的命令以获得等效效果。

注意:此方法是 Windows 操作系统独有的。在 Linux 上实现类似的效果,macOS 参考Linux 中的 Kill 命令

防范措施

终止一个同时运行的进程应该适当且有良心地完成。由于终止必要的进程(例如 svhost、System、Windows Explorer、Antimalware Service Executable)可能会导致操作系统功能不一致,从而导致系统崩溃、蓝屏死机、软件故障等。因此通常是建议事先仔细检查要终止的应用程序/PID 的名称。

方法一:

首先,我们将使用 wmi 库来获取正在运行的进程的列表,然后使用这个列表来搜索我们想要的进程,如果找到就会终止它。为了安装模块,请在操作系统的命令解释器中执行以下命令:

pip install wmi

代码:

Python3
# import wmi library
import wmi
 
# This variable ti would be used
# as a parity and counter for the
# terminating processes
ti = 0
 
# This variable stores the name
# of the process we are terminating
# The extension should also be
# included in the name
name = 'Process_Name'
 
# Initializing the wmi object
f = wmi.WMI()
  
# Iterating through all the
# running processes
for process in f.Win32_Process():
     
    # Checking whether the process
    # name matches our specified name
    if process.name == name:
 
        # If the name matches,
        # terminate the process   
        process.Terminate()
     
        # This increment would acknowledge
        # about the termination of the
        # Processes, and would serve as
        # a counter of the number of processes
        # terminated under the same name
        ti += 1
 
 
# True only if the value of
# ti didn't get incremented
# Therefore implying the
# process under the given
# name is not found
if ti == 0:
 
    # An output to inform the
    # user about the error
    print("Process not found!!!")


Python3
# import os module
import os
 
# delete given process
os.system('wmic process where name="Process_Name" delete')


解释:

首先,我们定义一个存储整数值的变量,它可以用来判断进程是否终止。此变量还可用于确定有多少同名进程已终止。然后,我们指定我们愿意终止的进程的名称。之后我们初始化 wmi 库的 WMI() 类。这使我们可以使用其中的方法,例如 WMI.Win32_Service、WMI.Win32_Process 等,这些方法旨在执行不同的任务。我们将使用WMI.Win32_Process函数来获取正在运行的进程列表作为 wmi 对象。然后我们使用wmi对象的name属性来获取正在运行的进程的名字。之后,我们将使用原始字符串匹配来确定应用程序的名称是否与之前指定的名称匹配。如果是这样,那么我们调用 Terminate() 方法来终止/终止进程。之后我们增加 ti 的值,其中增加的值(或任何非 0 值)将表示至少一个进程已终止。循环结束后(当所有正在运行的进程名称都已检查完毕),我们将检查变量 ti 的值是否仍为 0。如果是,则没有进程被终止,我们会使用错误消息通知用户。

方法二:

现在我们将使用 Windows 命令处理器中的一个内置实用程序,名为WMIC (Windows Management Instrumentation 命令行)来终止正在运行的进程。我们将使用的命令:

wmic process where name="Process_Name" delete

其中 Process_Name 是我们要终止的进程的名称。为了在Python中实现这个实用程序,我们将使用os.system()创建一个 Windows 命令行实例,并在那里执行命令(绕过它作为参数)。
代码:

Python3

# import os module
import os
 
# delete given process
os.system('wmic process where name="Process_Name" delete')

输出: