To get Parent and ChildProcess ID from process ID in Python

User007 picture User007 · Nov 29, 2013 · Viewed 12.5k times · Source

I am trying to get the ppid of the process that I want.

I used following code to get the pid

proc=subprocess.Popen('ps -ae | grep ruby', shell=True, stdout=subprocess.PIPE, )
output=proc.communicate()[0]
str = output.split()

Now in the str[0], I have the pid of the process say ruby, I want to get the parent process ID ppid and child process ID of the same process.

I need this solution to be run on Solaris as well as Red Hat Enterprise Linux 6.0

Is there any way to get that like getppid() and getchildid()? Or do I need to do it by grep command again and splitting?

Answer

Arovit picture Arovit · Nov 29, 2013

Using this code is a bad idea. Your code will not work on solaris. You can use 'psutil' library, that way you can keep your code independent of os. https://github.com/giampaolo/psutil

p = psutil.Process(7055)
parent_pid = p.ppid()