processes.processes_graph_model()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 36
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 21
nop 0
dl 0
loc 36
rs 8.4426
c 0
b 0
f 0
1
"""
2
Example: Processes Graph
3
This example demonstrates how to create a graph model representing
4
processes and their parent-child relationships using the `psutil` library.
5
"""
6
7
import operator
8
from collections.abc import Iterable
9
10
import networkx as nx
11
import psutil
12
13
import graphinate
14
15
16
def processes_graph_model():
17
    """
18
    Create a graph model representing processes and their parent-child relationships.
19
20
    Returns:
21
        GraphModel: A graph model representing processes and their parent-child relationships.
22
    """
23
24
    graph_model = graphinate.model("Processes Graph")
25
26
    def processes() -> Iterable[psutil.Process]:
27
        for pid in psutil.pids():
28
            if psutil.pid_exists(pid):
29
                yield psutil.Process(pid)
30
31
    processes_list = [
32
        {
33
            'pid': p.pid,
34
            'name': p.name(),
35
            'parent_pid': p.parent().pid if p.parent() else None
36
        }
37
        for p in processes()
38
    ]
39
40
    @graph_model.node(key=operator.itemgetter('pid'), label=operator.itemgetter('name'))
41
    def process():
42
        yield from processes_list
43
44
    @graph_model.edge()
45
    def edge():
46
        for p in processes_list:
47
            parent_pid = p.get('parent_pid')
48
            if parent_pid:
49
                yield {'source': p.get('pid'), 'target': parent_pid}
50
51
    return graph_model
52
53
54
model = processes_graph_model()
55
56
if __name__ == '__main__':
57
    # 1. Define Graph Builder
58
    builder = graphinate.builders.NetworkxBuilder(model=model)
59
60
    # Then
61
    # 2. Build the Graph object
62
    graph: nx.Graph = builder.build()
63
64
    # Then
65
    # 3. Option A - Output to console
66
    print(graph)
67
68
    # Or
69
    # 3. Option B - Output as a plot
70
    graphinate.renderers.matplotlib.plot(graph)
71