Обслуживание системы

Состояние батареи и износ

Показывает заряд, питание от сети, остаток времени, износ и число циклов батареи.

Python Windows macOS Linux Средний
Скачать battery_health.py
Описание

Что делает скрипт

Скрипт читает данные через psutil, а на Linux, macOS и Windows дополняет их сведениями о ёмкости из sysfs, ioreg или CIM. Если батареи нет, выводится понятное сообщение. Отчёт можно сохранить в JSON; настройки питания не меняются.

Запуск

Быстрый старт

python battery_health.py

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python battery_health.py
  • python battery_health.py --json reports/battery.json
Зависимости

Что понадобится

Python 3.10+ Интерпретатор Python 3.10 или новее
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
psutil Кроссплатформенный сбор данных о процессах, памяти и датчиках
Windows py -m pip install psutil
macOS python3 -m pip install psutil
Linux python3 -m pip install psutil
PowerShell 5.1+ Встроен в Windows 10 и 11
Windows Встроен в Windows 10/11 (PowerShell 5.1)
Исходник

battery_health.py

#!/usr/bin/env python3
"""Состояние батареи: заряд, питание, износ и циклы."""
from __future__ import annotations

import argparse
import json
import platform
import re
import subprocess
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_int(path: Path) -> int | None:
    try:
        return int(path.read_text(encoding="utf-8").strip())
    except (OSError, ValueError):
        return None


def linux_details() -> dict:
    for base in sorted(Path("/sys/class/power_supply").glob("BAT*")):
        full = read_int(base / "energy_full") or read_int(base / "charge_full")
        design = read_int(base / "energy_full_design") or read_int(base / "charge_full_design")
        cycles = read_int(base / "cycle_count")
        details = {"source": str(base), "cycles": cycles}
        if full and design and design > 0:
            details["full_capacity"] = full
            details["design_capacity"] = design
            details["health_percent"] = round(full / design * 100, 1)
        return details
    return {}


def macos_details() -> dict:
    result = subprocess.run(
        ["ioreg", "-r", "-c", "AppleSmartBattery"],
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode != 0:
        return {}
    details: dict = {"source": "ioreg"}
    for key in ("CycleCount", "DesignCapacity", "MaxCapacity", "AppleRawMaxCapacity"):
        match = re.search(rf'"{key}"\s*=\s*(\d+)', result.stdout)
        if match:
            details[key] = int(match.group(1))
    design = details.get("DesignCapacity")
    maximum = details.get("AppleRawMaxCapacity") or details.get("MaxCapacity")
    if design and maximum and maximum > 100:
        details["health_percent"] = round(maximum / design * 100, 1)
    return details


def windows_details() -> dict:
    script = (
        "Get-CimInstance Win32_Battery | Select-Object -First 1 "
        "DesignCapacity,FullChargeCapacity,EstimatedChargeRemaining,BatteryStatus | ConvertTo-Json -Compress"
    )
    result = subprocess.run(
        ["powershell", "-NoProfile", "-Command", script],
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode != 0 or not result.stdout.strip():
        return {}
    try:
        data = json.loads(result.stdout)
    except json.JSONDecodeError:
        return {}
    details = {"source": "Win32_Battery"}
    design = data.get("DesignCapacity")
    full = data.get("FullChargeCapacity")
    if design and full and design > 0:
        details["design_capacity"] = int(design)
        details["full_capacity"] = int(full)
        details["health_percent"] = round(full / design * 100, 1)
    return details


def platform_details() -> dict:
    system = platform.system()
    if system == "Linux":
        return linux_details()
    if system == "Darwin":
        return macos_details()
    if system == "Windows":
        return windows_details()
    return {}


def format_seconds(value: float | int | None) -> str:
    if value is None:
        return "неизвестно"
    if value == psutil.POWER_TIME_UNLIMITED:
        return "без ограничения"
    if value == psutil.POWER_TIME_UNKNOWN or value < 0:
        return "неизвестно"
    hours, remainder = divmod(int(value), 3600)
    minutes = remainder // 60
    return f"{hours} ч {minutes} мин"


def main() -> int:
    parser = argparse.ArgumentParser(description="Состояние батареи и износ")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    args = parser.parse_args()

    try:
        battery = psutil.sensors_battery()
    except (AttributeError, NotImplementedError):
        battery = None

    details = platform_details()
    if battery is None and not details:
        print("Батарея не найдена. Возможно, это настольный компьютер.")
        if args.json:
            payload = {
                "generated": datetime.now().isoformat(timespec="seconds"),
                "platform": platform.system(),
                "battery_present": False,
                "details": {},
            }
            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}")
        return 0

    data: dict = {
        "generated": datetime.now().isoformat(timespec="seconds"),
        "platform": platform.system(),
        "battery_present": True,
        "details": details,
    }
    if battery is not None:
        data.update(
            {
                "percent": round(battery.percent, 1),
                "plugged": battery.power_plugged,
                "seconds_left": battery.secsleft,
            }
        )
        print(f"Заряд: {data['percent']}%")
        print(f"Питание: {'от сети' if battery.power_plugged else 'от батареи'}")
        print(f"Остаток: {format_seconds(battery.secsleft)}")
    else:
        print("Заряд: данные psutil недоступны")

    if details.get("health_percent") is not None:
        print(f"Износ: здоровье {details['health_percent']}%")
    if details.get("cycles") is not None:
        print(f"Циклов зарядки: {details['cycles']}")
    if details.get("full_capacity") and details.get("design_capacity"):
        print(f"Ёмкость: {details['full_capacity']} из {details['design_capacity']}")

    if args.json:
        args.json.parent.mkdir(parents=True, exist_ok=True)
        args.json.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        print(f"JSON сохранён: {args.json}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        print("Прервано пользователем", file=sys.stderr)
        raise SystemExit(130)

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get system-battery-health
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Обслуживание системы

Диагностика, обновления, службы, логи и обслуживание компьютеров.