-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem_info.py
More file actions
75 lines (63 loc) · 2.16 KB
/
system_info.py
File metadata and controls
75 lines (63 loc) · 2.16 KB
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
import platform
import shutil
import time
from pathlib import Path
try:
import psutil # type: ignore
except Exception: # noqa: BLE001
psutil = None
def _human_bytes(num: float) -> str:
for unit in ["B", "KB", "MB", "GB", "TB"]:
if num < 1024:
return f"{num:.1f} {unit}"
num /= 1024.0
return f"{num:.1f} PB"
def get_system_snapshot(cpu_interval: float = 0.0) -> dict:
info = {
"os": f"{platform.system()} {platform.release()}",
"python": platform.python_version(),
"uptime": "N/A",
"cpu": "N/A",
"ram": "N/A",
"disk": "N/A",
"battery": "N/A",
"processes": "N/A",
}
if psutil is not None:
try:
boot_time = psutil.boot_time()
uptime_seconds = int(time.time() - boot_time)
hours = uptime_seconds // 3600
minutes = (uptime_seconds % 3600) // 60
info["uptime"] = f"{hours}h {minutes}m"
except Exception: # noqa: BLE001
pass
try:
info["cpu"] = f"{psutil.cpu_percent(interval=cpu_interval):.1f}%"
except Exception: # noqa: BLE001
pass
try:
mem = psutil.virtual_memory()
info["ram"] = f"{mem.percent:.1f}% ({_human_bytes(mem.used)} / {_human_bytes(mem.total)})"
except Exception: # noqa: BLE001
pass
try:
disk = psutil.disk_usage(str(Path.home()))
info["disk"] = f"{disk.percent:.1f}% ({_human_bytes(disk.used)} / {_human_bytes(disk.total)})"
except Exception: # noqa: BLE001
pass
try:
bat = psutil.sensors_battery()
if bat is not None:
charging = " (charging)" if bat.power_plugged else ""
info["battery"] = f"{bat.percent:.1f}%{charging}"
except Exception: # noqa: BLE001
pass
try:
info["processes"] = str(len(psutil.pids()))
except Exception: # noqa: BLE001
pass
else:
total, used, _free = shutil.disk_usage(Path.home())
info["disk"] = f"{_human_bytes(used)} / {_human_bytes(total)}"
return info