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