方法 1:使用多功能“os”模块“os”模块是 python 与操作系统交互的基石,拥有丰富的功能。其中,system()函数提供了执行操作系统命令的网关。值得注意的是,windows 利用“taskkill”命令来终止活动进程。
示例:利用“os”模块在接下来的示例中,我们将使用 `os` 模块来终止古老的记事本应用程序:
import os# the process name to be brought to an abrupt haltprocess_name = notepad.exe# employing the taskkill command to terminate the processresult = os.system(ftaskkill /f /im {process_name})if result == 0: print(finstance deletion successful: {process_name})else: print(error occurred while deleting the instance.)
输出deleting instance \desktop-li99o93\root\cimv2:win32_process.handle=1234instance deletion successful.
此说明性代码片段使用“taskkill”命令以及“/f”(强制)和“/im”(映像名称)标志来强制终止由指定映像名称标识的进程。
方法 2:利用强大的“psutil”库“psutil”库提供了一个强大的跨平台工具库,用于访问系统信息和操作正在运行的进程。在深入研究 `psutil` 的使用之前,我们必须首先通过执行以下安装命令来确保它的存在:
pip install psutil
成功安装后,我们就可以使用“psutil”的功能来终止活动进程。
示例:利用“psutil”库在接下来的示例中,我们将使用 `psutil` 库来终止著名的记事本应用程序:
import psutil# the process name to be terminatedprocess_name = notepad.exe# iterating through all running processesfor 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(finstance deletion successful: {process_info}) except (psutil.nosuchprocess, psutil.accessdenied, psutil.zombieprocess): # prudently handling potential exceptions arising during process information retrieval pass
输出deleting instance \desktop-li99o93\root\cimv2:win32_process.handle=5678instance deletion successful.
此示例片段阐明了我们的方法:我们使用“psutil.process_iter()”迭代所有正在运行的进程。通过使用 as_dict() 方法,我们以命名元组的形式获取进程信息。如果进程名称与目标进程一致,我们会立即通过“terminate()”方法终止它。
方法 3:释放“子流程”模块的力量python 的“子进程”模块使我们能够生成新进程、与其输入/输出/错误管道建立连接以及检索其返回代码。我们可以利用该模块执行“taskkill”命令并有效终止正在运行的进程。
示例:利用“子流程”模块在本例中,我们将演示使用强大的“子进程”模块终止记事本应用程序:
import subprocess# the process name to be terminatedprocess_name = notepad.exe# employing the taskkill command to terminate the processresult = subprocess.run(ftaskkill /f /im {process_name}, shell=true)if result.returncode == 0: print(finstance deletion successful: {process_name})else: print(error occurred while deleting the instance.)
输出deleting instance \desktop-li99o93\root\cimv2:win32_process.handle=9012instance deletion successful.
在此示例中,我们依靠“subprocess.run()”函数来执行带有“/f”和“/im”标志的“taskkill”命令。在 windows 命令 shell 中执行命令时,“shell=true”参数变得不可或缺。
结论通过这次深入探索,我们阐明了使用 python 终止 windows 上正在运行的进程的三种不同方法。通过采用“os”模块,我们可以执行操作系统命令。 “psutil”库作为一个强大的工具出现,为我们提供了用于系统信息检索和流程操作的全面的跨平台解决方案。此外,“subprocess”模块解锁了新的维度,使我们能够毫不费力地生成进程并执行命令。
每种方法都有其自身的优点,适合特定的项目要求。在进行进程终止工作时,必须谨慎行事并了解由此带来的潜在风险,例如数据丢失或系统不稳定。
以上就是如何在python中终止正在运行的windows进程?的详细内容。
