Skip to content Skip to sidebar Skip to footer

How Do You List All Child Processes In Python?

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?

Solution 1:

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

Solution 2:

It's usually safer to log the pids of all your child processes when you create them. There isn't a posix compliant way to list child PIDs. I know this can be done with the PS tool.

Solution 3:

It sounds like psutil is the recommended method. If, however, you don't want to depend on an external library, you can use the --ppid of the ps command to filter processes by parent id. (Assuming you're running on an OS with ps, of course.)

Here's a snippet that shows how to call it:

ps_output = run(['ps', '-opid', '--no-headers', '--ppid', str(os.getpid())],
                stdout=PIPE, encoding='utf8')
child_process_ids = [int(line) for line in ps_output.stdout.splitlines()]

Solution 4:

Using psutil you can get all children process (even recursive process) look at https://psutil.readthedocs.io/en/latest/#psutil.Process.children

Post a Comment for "How Do You List All Child Processes In Python?"