python_打印pstree效果

from subprocess import PIPE,Popen
import shlex

def pstree():
	cmd = 'ps ax -o pid,ppid,command'
	sub = Popen(shlex.split(cmd),stdout=PIPE)
	return sub.stdout.readlines()[1:]

def parse_ps(string):
	list_ps = []
	for i in string:
		l = i.split()
		ps = {'pid':int(l[0]),'ppid':int(l[1]),'command':' '.join(l[2:])}
		list_ps.append(ps)
	return list_ps
def show(pid,d,depth=3):
	show_root = [ i for i in d if i['pid'] == pid ][0]
	print '-'*depth,show_root['pid'],show_root['ppid'],show_root['command']
	show_child = [ i for i in d if i['ppid'] == pid ]
	depth += 3
	for i in show_child:
		show(i['pid'],d,depth)

if __name__ == '__main__':
	show(1,parse_ps(pstree()),3)


你可能感兴趣的:(python)