在Linux中使用python创建类似于pstree命令的进程树

Zac*_*ary 5 python tree dictionary process

我是python的新手。我想编写一个在上输出树状图形的程序stdout。我理想的输出是:

0
|__0
|__4
|  |__360
|      |__1000
272
|__3460
Run Code Online (Sandbox Code Playgroud)

我收集的数据如下:

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]
Run Code Online (Sandbox Code Playgroud)

左列是父进程ID,右列是子进程ID。我将数据放在名为的字典中dic。因此,字典key是父进程ID,而字典value是由子进程ID组成的列表。

我的代码是这样的:

for key in dic.keys():
    print key, '\n|'
    for v in dic[key]:
        print '__', v, '\n|'
Run Code Online (Sandbox Code Playgroud)

问题是我只能输出两层树。以数据为例,576因为父ID也是的子ID 472。因此576,应该将664、672放在472的子树中。我的代码对此无效。似乎我们需要使用递归函数。但是我不知道如何处理。

你们能给我提示吗?


编辑:从我收集的数据来看,有一些没有祖父母的父母ID。因此,最终的产出应该是一片森林。没有一棵单根的树。

Alf*_*lfe 4

这个怎么样:

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
Run Code Online (Sandbox Code Playgroud)

也许这就是你喜欢的方式,我不知道。

它没有内置任何递归检查,因此如果您尝试使用它0,它将陷入无限递归(并最终由于堆栈溢出而中止)。您可以通过传递已处理节点的跟踪来自行检查递归。

这也不会找到您森林中的树根列表,因此您也必须这样做。(但这听起来像是另一个问题。)

  • 这是使用 psutil 的类似 pstree 的脚本,它基于您的代码(谢谢):https://github.com/giampaolo/psutil/blob/master/examples/pstree.py (2认同)