#!/usr/bin/env python
import shlex
from subprocess import Popen,PIPE
def get_ps():
cmd = ‘ps ax -o pid,ppid,cmd‘
p = Popen(shlex.split(cmd),stdout=PIPE)
return p.stdout.readlines()[1:]
def split(s):
s = s.split()
return s[0],s[1],‘‘.join(s[2:])
def parser_ps(data):
procs = []
for l in data:
pid,ppid,cmd = [i.strip() for i in split(l)]
procs.append({‘pid‘:int(pid),‘ppid‘:int(ppid),‘cmd‘:cmd})
return procs
def show(pid,procs,depth=1):
root = [p for p in procs if p[‘pid‘] == pid][0]
print ‘-‘ * depth,root[‘pid‘],root[‘ppid‘],root[‘cmd‘]
childs = [proc for proc in procs if proc[‘ppid‘] == pid]
if childs:
depth += 1
for c in childs:
show(c[‘pid‘],procs,depth)
if __name__ == ‘__main__‘:
data = get_ps()
procs = parser_ps(data)
show(1,procs)
本文出自 “muzinan的技术博客” 博客,谢绝转载!