python_打印pstree效果

来源:互联网 发布:触摸查询软件 编辑:程序博客网 时间:2024/06/16 20:19
from subprocess import PIPE,Popenimport shlexdef 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_psdef 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 += 3for i in show_child:show(i['pid'],d,depth)if __name__ == '__main__':show(1,parse_ps(pstree()),3)


原创粉丝点击