Create a process tree, e.g. pstree command with python on linux

I am new to python. I want to write a program that displays a tree drawing on stdout . My ideal output is as follows:

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

The data I have collected is as 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 is the identifier of the parent process, and the right column is the child identifier of the process. I put data into a dictionary called dic . Thus, the key dictionary is the identifier of the parent process, and the value dictionary is a list of identifiers of the child processes.

My code looks like this:

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

The question is that I can only output two layer trees. Take the data, for example, 576 , since the parent identifier is also a child identifier of 472 . Therefore, 576 , 664, 672 should be placed in subtree 472. My code does not work for this. It seems that we need to use recursive functions. But I don’t know how to handle this.

Could you guys give me clues?


EDIT: From the data I collected, there are some parent identifiers that don't have a parent. So the end result should be a forest. Not selected root tree.

+4
source share
1 answer

How about this:

 def printTree(parent, tree, indent=''): print parent if parent not in tree: return for 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 how you like it, I don’t know.

It has no checks built-in for recursions, so if you try it at 0 , it will run into infinite recursion (and ultimately because). You can check the recursion yourself by going through the tracing of already processed nodes.

It also does not find the list of tree roots in your forest, so you also have to do this. (But that sounds like another question.)

+3
source

Source: https://habr.com/ru/post/1479327/


All Articles