#!/usr/bin/env python3 """Температурные датчики и вентиляторы.""" from __future__ import annotations import argparse import json import sys from datetime import datetime from pathlib import Path try: import psutil except ImportError: print("Нужен psutil: python -m pip install psutil", file=sys.stderr) raise SystemExit(2) def read_sensors() -> tuple[dict, dict]: temperatures: dict = {} fans: dict = {} try: temperatures = psutil.sensors_temperatures(fahrenheit=False) or {} except (AttributeError, NotImplementedError, OSError): temperatures = {} try: fans = psutil.sensors_fans() or {} except (AttributeError, NotImplementedError, OSError): fans = {} return temperatures, fans def main() -> int: parser = argparse.ArgumentParser(description="Температурные датчики") parser.add_argument("--warn", type=float, help="Порог предупреждения в градусах") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() temperatures, fans = read_sensors() if not temperatures and not fans: print("Датчики не найдены.") print("На Linux установите lm-sensors и выполните sensors-detect.") print("На Windows и macOS поддержка зависит от драйверов и модели.") return 0 over_limit = False for chip, entries in temperatures.items(): print(f"{chip}:") for entry in entries: label = entry.label or "без имени" current = entry.current suffix = "" if entry.high is not None: suffix += f", high {entry.high:.0f}" if entry.critical is not None: suffix += f", critical {entry.critical:.0f}" print(f" {label}: {current:.1f} C{suffix}") if args.warn is not None and current >= args.warn: over_limit = True for chip, entries in fans.items(): print(f"Вентиляторы {chip}:") for entry in entries: label = entry.label or "без имени" print(f" {label}: {entry.current} об/мин") if args.json: payload = { "generated": datetime.now().isoformat(timespec="seconds"), "temperatures": { chip: [ { "label": item.label, "current": item.current, "high": item.high, "critical": item.critical, } for item in entries ] for chip, entries in temperatures.items() }, "fans": { chip: [{"label": item.label, "current": item.current} for item in entries] for chip, entries in fans.items() }, } args.json.parent.mkdir(parents=True, exist_ok=True) args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"JSON сохранён: {args.json}") if over_limit: print("Есть датчики выше заданного порога.", file=sys.stderr) return 1 return 0 if __name__ == "__main__": try: raise SystemExit(main()) except KeyboardInterrupt: print("Прервано пользователем", file=sys.stderr) raise SystemExit(130)