Rowan
Rowan

Reputation: 924

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?

Upvotes: 44

Views: 38935

Answers (4)

Jason Martens
Jason Martens

Reputation: 1355

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

Upvotes: 59

Don Kirkby
Don Kirkby

Reputation: 56660

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

Upvotes: 3

Ravi Gadhia
Ravi Gadhia

Reputation: 488

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

Upvotes: 0

Zac Bowling
Zac Bowling

Reputation: 6588

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.

Upvotes: 5

Related Questions