你如何在python中列出所有子进程? [英] How do you list all child processes in python?

查看:46
本文介绍了你如何在python中列出所有子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用启动各种子进程的第三方库.当出现异常时,我想杀死所有子进程.如何获取子 pid 列表?

I'm using a third party library that starts various sub processes. When there's an exception I'd like to kill all the child processes. How can I get a list of child pids?

推荐答案

您不能总是在创建子进程时记录所有子进程,因为它们会反过来创建您不知道的新进程.但是,使用 psutil 查找它们非常简单:

You can't always log all the sub-processes as they are created, since they can in turn create new processes that you are not aware of. However, it's pretty simple to use psutil to find them:

import psutil

current_process = psutil.Process()
children = current_process.children(recursive=True)
for child in children:
    print('Child pid is {}'.format(child.pid))

这篇关于你如何在python中列出所有子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆