Debian Codegraph @

examples/top_lite_simulator.py

raw
1 """Lite simulation of the top linux command."""
2 import datetime
3 import random
4 import time
5 from dataclasses import dataclass
6
7 from rich import box
8 from rich.console import Console
9 from rich.live import Live
10 from rich.table import Table
11 from typing import Literal
12
13
14 @dataclass
15 class Process:
16 pid: int
17 command: str
18 cpu_percent: float
19 memory: int
20 start_time: datetime.datetime
21 thread_count: int
22 state: Literal["running", "sleeping"]
23
24 @property
25 def memory_str(self) -> str:
26 if self.memory > 1e6:
27 return f"{int(self.memory/1e6)}M"
28 if self.memory > 1e3:
29 return f"{int(self.memory/1e3)}K"
30 return str(self.memory)
31
32 @property
33 def time_str(self) -> str:
34 return str(datetime.datetime.now() - self.start_time)
35
36
37 def generate_process(pid: int) -> Process:
38 return Process(
39 pid=pid,
40 command=f"Process {pid}",
41 cpu_percent=random.random() * 20,
42 memory=random.randint(10, 200) ** 3,
43 start_time=datetime.datetime.now()
44 - datetime.timedelta(seconds=random.randint(0, 500) ** 2),
45 thread_count=random.randint(1, 32),
46 state="running" if random.randint(0, 10) < 8 else "sleeping",
47 )
48
49
50 def create_process_table(height: int) -> Table:
51 processes = sorted(
52 [generate_process(pid) for pid in range(height)],
53 key=lambda p: p.cpu_percent,
54 reverse=True,
55 )
56 table = Table(
57 "PID", "Command", "CPU %", "Memory", "Time", "Thread #", "State", box=box.SIMPLE
58 )
59
60 for process in processes:
61 table.add_row(
62 str(process.pid),
63 process.command,
64 f"{process.cpu_percent:.1f}",
65 process.memory_str,
66 process.time_str,
67 str(process.thread_count),
68 process.state,
69 )
70
71 return table
72
73
74 console = Console()
75
76 with Live(console=console, screen=True, auto_refresh=False) as live:
77 while True:
78 live.update(create_process_table(console.size.height - 4), refresh=True)
79 time.sleep(1)