psutil

Форк
0
/
pstree.py 
71 строка · 1.7 Кб
1
#!/usr/bin/env python3
2

3
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
4
# Use of this source code is governed by a BSD-style license that can be
5
# found in the LICENSE file.
6

7
"""Similar to 'ps aux --forest' on Linux, prints the process list
8
as a tree structure.
9

10
$ python3 scripts/pstree.py
11
0 ?
12
|- 1 init
13
| |- 289 cgmanager
14
| |- 616 upstart-socket-bridge
15
| |- 628 rpcbind
16
| |- 892 upstart-file-bridge
17
| |- 907 dbus-daemon
18
| |- 978 avahi-daemon
19
| | `_ 979 avahi-daemon
20
| |- 987 NetworkManager
21
| | |- 2242 dnsmasq
22
| | `_ 10699 dhclient
23
| |- 993 polkitd
24
| |- 1061 getty
25
| |- 1066 su
26
| | `_ 1190 salt-minion...
27
...
28
"""
29

30
from __future__ import print_function
31

32
import collections
33
import sys
34

35
import psutil
36

37

38
def print_tree(parent, tree, indent=''):
39
    try:
40
        name = psutil.Process(parent).name()
41
    except psutil.Error:
42
        name = "?"
43
    print(parent, name)
44
    if parent not in tree:
45
        return
46
    children = tree[parent][:-1]
47
    for child in children:
48
        sys.stdout.write(indent + "|- ")
49
        print_tree(child, tree, indent + "| ")
50
    child = tree[parent][-1]
51
    sys.stdout.write(indent + "`_ ")
52
    print_tree(child, tree, indent + "  ")
53

54

55
def main():
56
    # construct a dict where 'values' are all the processes
57
    # having 'key' as their parent
58
    tree = collections.defaultdict(list)
59
    for p in psutil.process_iter():
60
        try:
61
            tree[p.ppid()].append(p.pid)
62
        except (psutil.NoSuchProcess, psutil.ZombieProcess):
63
            pass
64
    # on systems supporting PID 0, PID 0's parent is usually 0
65
    if 0 in tree and 0 in tree[0]:
66
        tree[0].remove(0)
67
    print_tree(min(tree), tree)
68

69

70
if __name__ == '__main__':
71
    main()
72

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.