-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysglance.py
More file actions
354 lines (301 loc) · 11.5 KB
/
Copy pathsysglance.py
File metadata and controls
354 lines (301 loc) · 11.5 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python3
"""sysglance - a tiny, zero-dependency snapshot of your system.
Prints CPU, memory, disk, network, battery, temperature, OS, and uptime
using only the Python standard library. Works on Linux, macOS, and Windows.
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import shutil
import socket
import sys
import time
__version__ = "0.2.1"
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[36m"
GREEN = "\033[32m"
def supports_color() -> bool:
return sys.stdout.isatty() and os.name != "nt"
def paint(text: str, color: str, enable: bool) -> str:
return f"{color}{text}{RESET}" if enable else text
def human_bytes(n: float) -> str:
for unit in ("B", "KB", "MB", "GB", "TB", "PB"):
if n < 1024.0:
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
n /= 1024.0
return f"{n:.1f} EB"
def fmt_uptime(secs: float | None) -> str:
if secs is None:
return "n/a"
secs = int(secs)
days, rem = divmod(secs, 86400)
hours, rem = divmod(rem, 3600)
mins, _ = divmod(rem, 60)
parts = []
if days:
parts.append(f"{days}d")
if hours:
parts.append(f"{hours}h")
parts.append(f"{mins}m")
return " ".join(parts)
def cpu_model() -> str:
"""Best-effort CPU model name across platforms."""
try:
with open("/proc/cpuinfo") as fh:
for line in fh:
if line.lower().startswith("model name"):
return line.split(":", 1)[1].strip()
except OSError:
pass
system = platform.system()
if system == "Darwin":
try:
import subprocess
out = subprocess.check_output(
["sysctl", "-n", "machdep.cpu.brand_string"], text=True
)
return out.strip()
except Exception:
pass
elif system == "Windows":
ident = os.environ.get("PROCESSOR_IDENTIFIER")
if ident:
return ident
return platform.processor() or "Unknown CPU"
def mem_info() -> tuple[int | None, int | None]:
"""Return (total_bytes, available_bytes), or (None, None) if unknown."""
try:
fields = {}
with open("/proc/meminfo") as fh:
for line in fh:
key, _, val = line.partition(":")
fields[key.strip()] = val.strip()
total = int(fields["MemTotal"].split()[0]) * 1024
avail = int(fields.get("MemAvailable", fields["MemFree"]).split()[0]) * 1024
return total, avail
except (OSError, KeyError, ValueError, IndexError):
pass
if platform.system() == "Windows":
try:
import ctypes
class MemoryStatusEx(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong),
]
status = MemoryStatusEx()
status.dwLength = ctypes.sizeof(MemoryStatusEx)
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
return int(status.ullTotalPhys), int(status.ullAvailPhys)
except Exception:
pass
return None, None
def uptime_seconds() -> float | None:
try:
with open("/proc/uptime") as fh:
return float(fh.read().split()[0])
except (OSError, ValueError, IndexError):
pass
system = platform.system()
if system == "Darwin":
try:
import subprocess
out = subprocess.check_output(["sysctl", "-n", "kern.boottime"], text=True)
boot = int(out.split("sec =")[1].split(",")[0])
return max(0.0, time.time() - boot)
except Exception:
pass
elif system == "Windows":
try:
import ctypes
return ctypes.windll.kernel32.GetTickCount64() / 1000.0
except Exception:
pass
return None
def network_info() -> dict:
"""Primary outbound IP and the list of interface names, where available."""
info: dict = {"primary_ip": None, "interfaces": []}
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.settimeout(0.2)
# No packets are sent for a UDP "connect"; it just selects the route
# the kernel would use, which reveals the primary local address.
sock.connect(("8.8.8.8", 80))
info["primary_ip"] = sock.getsockname()[0]
except OSError:
pass
finally:
sock.close()
try:
info["interfaces"] = [name for _, name in socket.if_nameindex()]
except (OSError, AttributeError):
pass
return info
def battery_info() -> dict | None:
"""Battery percentage and status, or None if there's no battery."""
base = "/sys/class/power_supply"
try:
for entry in sorted(os.listdir(base)):
if entry.startswith("BAT"):
with open(os.path.join(base, entry, "capacity")) as fh:
percent = int(fh.read().strip())
status = "Unknown"
try:
with open(os.path.join(base, entry, "status")) as fh:
status = fh.read().strip()
except OSError:
pass
return {"percent": percent, "status": status}
except OSError:
pass
system = platform.system()
if system == "Windows":
try:
import ctypes
# These four fields are unsigned BYTEs in the Win32 API. Using a
# signed type here would wrap the 255 "no battery" sentinel to -1.
class SystemPowerStatus(ctypes.Structure):
_fields_ = [
("ACLineStatus", ctypes.c_ubyte),
("BatteryFlag", ctypes.c_ubyte),
("BatteryLifePercent", ctypes.c_ubyte),
("SystemStatusFlag", ctypes.c_ubyte),
("BatteryLifeTime", ctypes.c_ulong),
("BatteryFullLifeTime", ctypes.c_ulong),
]
status = SystemPowerStatus()
if ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(status)):
percent = status.BatteryLifePercent
# 255 = unknown; BatteryFlag bit 7 (128) = no system battery.
if percent == 255 or percent > 100 or status.BatteryFlag == 128:
return None
charging = status.ACLineStatus == 1
return {"percent": int(percent), "status": "Charging" if charging else "Discharging"}
except Exception:
pass
elif system == "Darwin":
try:
import re
import subprocess
out = subprocess.check_output(["pmset", "-g", "batt"], text=True)
match = re.search(r"(\d+)%", out)
if match:
charging = "discharging" not in out.lower() and "charging" in out.lower()
return {"percent": int(match.group(1)), "status": "Charging" if charging else "Discharging"}
except Exception:
pass
return None
def cpu_temp() -> float | None:
"""Highest CPU/thermal-zone temperature in Celsius (Linux), else None."""
base = "/sys/class/thermal"
try:
temps = []
for entry in os.listdir(base):
if entry.startswith("thermal_zone"):
try:
with open(os.path.join(base, entry, "temp")) as fh:
temps.append(int(fh.read().strip()) / 1000.0)
except (OSError, ValueError):
pass
if temps:
return round(max(temps), 1)
except OSError:
pass
return None
def collect() -> dict:
total, avail = mem_info()
disk = shutil.disk_usage(os.path.expanduser("~"))
user = os.environ.get("USER") or os.environ.get("USERNAME") or "unknown"
return {
"user": user,
"hostname": socket.gethostname(),
"os": {"system": platform.system(), "release": platform.release()},
"arch": platform.machine(),
"python": platform.python_version(),
"cpu": {"model": cpu_model(), "cores": os.cpu_count()},
"memory": (
{"total": total, "used": total - avail, "available": avail}
if total and avail is not None
else None
),
"disk": {"total": disk.total, "used": disk.used, "free": disk.free},
"uptime_seconds": uptime_seconds(),
"network": network_info(),
"battery": battery_info(),
"temperature_c": cpu_temp(),
}
def human_rows(data: dict) -> list[tuple[str, str]]:
rows = [
("User", f"{data['user']}@{data['hostname']}"),
("OS", f"{data['os']['system']} {data['os']['release']}".strip()),
("Arch", data["arch"]),
("Python", data["python"]),
("CPU", data["cpu"]["model"]),
("Cores", str(data["cpu"]["cores"] or "?")),
]
mem = data["memory"]
if mem:
pct = mem["used"] / mem["total"] * 100
rows.append(("Memory", f"{human_bytes(mem['used'])} / {human_bytes(mem['total'])} ({pct:.0f}%)"))
else:
rows.append(("Memory", "n/a"))
disk = data["disk"]
dpct = disk["used"] / disk["total"] * 100
rows.append(("Disk (~)", f"{human_bytes(disk['used'])} / {human_bytes(disk['total'])} ({dpct:.0f}%)"))
rows.append(("Uptime", fmt_uptime(data["uptime_seconds"])))
net = data["network"]
if net.get("primary_ip"):
rows.append(("IP", net["primary_ip"]))
ifaces = net.get("interfaces") or []
if ifaces:
# Some platforms (notably Windows) report dozens of pseudo-interfaces.
# Keep the table readable; the full list still lives in --json output.
shown = ifaces[:6]
label = ", ".join(shown)
if len(ifaces) > len(shown):
label += f", +{len(ifaces) - len(shown)} more"
rows.append(("Ifaces", label))
bat = data["battery"]
if bat:
rows.append(("Battery", f"{bat['percent']}% ({bat['status']})"))
temp = data["temperature_c"]
if temp is not None:
rows.append(("CPU Temp", f"{temp:.1f} C"))
return rows
def render(rows: list[tuple[str, str]], color: bool) -> None:
title = "sysglance"
rule = "-" * len(title)
if color:
print(f"{BOLD}{CYAN}{title}{RESET}")
print(f"{DIM}{rule}{RESET}")
else:
print(title)
print(rule)
width = max(len(key) for key, _ in rows)
for key, value in rows:
print(f"{paint(f'{key:<{width}}', GREEN, color)} {value}")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="A tiny snapshot of your system.")
parser.add_argument("--json", action="store_true", help="output as JSON")
parser.add_argument("--no-color", action="store_true", help="disable colored output")
parser.add_argument("--version", action="version", version=f"sysglance {__version__}")
args = parser.parse_args(argv)
data = collect()
if args.json:
print(json.dumps(data, indent=2))
else:
render(human_rows(data), supports_color() and not args.no_color)
return 0
if __name__ == "__main__":
raise SystemExit(main())