Python中通过进程名结束进程树

Python评论44阅读模式

在 Python 中,通过进程名结束进程树(即终止一个进程及其所有子进程)可以使用 psutil 库。psutil 是一个跨平台库,用于系统和进程管理。它提供了很多有用的方法来获取系统和进程的信息,以及控制进程。

以下是一个示例代码,演示如何通过进程名找到并终止进程树:文章源自爱尚资源教程网-https://www.23jcw.net/10232.html

1.安装 psutil 库(如果尚未安装):文章源自爱尚资源教程网-https://www.23jcw.net/10232.html

pip install psutil

2.使用 psutil 库结束进程树:文章源自爱尚资源教程网-https://www.23jcw.net/10232.html

import psutil  
import os  
import signal  

def kill_process_tree(pid, sig=signal.SIGTERM, include_parent=True):  
    """  
    Kill a process tree (including all children) with signal "sig" and optionally  
    the parent process as well.  
      
    :param pid: PID of the parent process.  
    :param sig: Signal to send to the processes.  
    :param include_parent: If True, also kill the parent process.  
    """  
    parent = psutil.Process(pid)  
    children = parent.children(recursive=True)  
    for child in children:  
        try:  
            os.kill(child.pid, sig)  
        except ProcessLookupError:  
            pass  
    if include_parent:  
        try:  
            os.kill(parent.pid, sig)  
        except ProcessLookupError:  
            pass  

def find_and_kill_process_by_name(process_name):  
    """  
    Find processes by name and kill them along with their children.  
      
    :param process_name: Name of the process to find and kill.  
    """  
    for proc in psutil.process_iter(['pid', 'name']):  
        try:  
            if proc.info['name'] == process_name:  
                kill_process_tree(proc.info['pid'])  
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):  
            pass  

if __name__ == "__main__":  
    process_name = "your_process_name_here"  # Replace with the actual process name  
    find_and_kill_process_by_name(process_name)

代码说明:
1.kill_process_tree 函数:
接受一个进程 ID (pid),一个信号 (sig,默认为 SIGTERM,表示终止进程),以及一个布尔值 (include_parent,表示是否也要终止父进程)。
使用 psutil.Process 创建一个进程对象,并获取其所有子进程(递归)。
遍历子进程并发送信号以终止它们。
如果 include_parent 为 True,则也终止父进程。
2.find_and_kill_process_by_name 函数:
遍历所有进程,查找与给定进程名匹配的进程。
对每个匹配的进程,调用 kill_process_tree 函数来终止该进程及其所有子进程。
3.主程序:
设置要终止的进程名。
调用 find_and_kill_process_by_name 函数。
注意事项:
权限:终止某些进程可能需要管理员权限。确保你的脚本有足够的权限来终止目标进程。
信号:SIGTERM 是终止进程的默认信号,但你可以根据需要选择其他信号(例如 SIGKILL)。
异常处理:代码中包含了异常处理,以应对可能的 psutil 异常(如 NoSuchProcess, AccessDenied, ZombieProcess)。
将 your_process_name_here 替换为你要终止的实际进程名,然后运行脚本。文章源自爱尚资源教程网-https://www.23jcw.net/10232.html 文章源自爱尚资源教程网-https://www.23jcw.net/10232.html

相关文章
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
  • 温馨提示:如遇到资源下载不了,或者文章没有解决你的问题的,可以联系我们帮你处理!!!
  • 转载请务必保留本文链接:https://www.23jcw.net/10232.html

发表评论