dictionary - Create a process tree like pstree command with python in linux -


i new python. want write program outputting tree-like drawing on stdout. ideal output like:

0 |__0 |__4 |  |__360 |      |__1000 272 |__3460 

the data collected follows:

0       : [0, 4] 4       : [360] 272     : [3460] 368     : [4184] 472     : [504, 576, 7016] 568     : [584, 640] 576     : [664, 672] 640     : [1048] 664     : [368, 372, 512, 788] 788     : [2120, 2720, 2976, 2996, 3956, 3980] 

the left column parent process id, , right column child process id. put data in dictionary called dic. dictionary key parent process id, , dictionary value list consisting of child process ids.

my code this:

for key in dic.keys():     print key, '\n|'     v in dic[key]:         print '__', v, '\n|' 

the question can output 2 layer tree. take data example, 576 parent id child id of 472. 576, 664, 672 should placed in sub-tree of 472. code doesn't work this. seems need use recursive functions. don't know how handle it.

could guys give me hints?


edit: data collected, there parent ids not have grand parent. ultimate output should forest. not singled rooted tree.

how this:

def printtree(parent, tree, indent=''):   print parent   if parent not in tree:     return   child in tree[parent][:-1]:     sys.stdout.write(indent + '|-')     printtree(child, tree, indent + '| ')   child = tree[parent][-1]   sys.stdout.write(indent + '`-')   printtree(child, tree, indent + '  ')  tree = {   0       : [0, 4],   4       : [360],   272     : [3460],   368     : [4184],   472     : [504, 576, 7016],   568     : [584, 640],   576     : [664, 672],   640     : [1048],   664     : [368, 372, 512, 788],   788     : [2120, 2720, 2976, 2996, 3956, 3980] }  printtree(472, tree)  printtree(472, tree) 472 |-504 |-576 | |-664 | | |-368 | | | `-4184 | | |-372 | | |-512 | | `-788 | |   |-2120 | |   |-2720 | |   |-2976 | |   |-2996 | |   |-3956 | |   `-3980 | `-672 `-7016 

maybe that's how it, don't know.

it not have checks built in recursions, if try on 0, run endless recursion (and abort due stack overflow). check recursions passing trace of processed nodes.

this not find list of tree roots in forest, have well. (but sounds question.)


Comments