macOS

Батарея, питание и температура

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

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

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

Скрипт объединяет pmset -g batt, pmset -g custom и ioreg AppleSmartBattery. Из вывода извлекаются циклы, проектная и фактическая ёмкость, температура и текущий режим питания. Это только диагностика, настройки энергосбережения не меняются.

Запуск

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

python3 power_report.py

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

Примеры

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

  • python3 power_report.py
  • python3 power_report.py --json power.json
Зависимости

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

Python 3.10+ Только стандартная библиотека
macOS brew install python
Исходник

power_report.py

#!/usr/bin/env python3
"""Батарея, настройки питания и температура macOS."""
from __future__ import annotations

import argparse
import json
import re
import subprocess
from pathlib import Path


def run(command: list[str]) -> str:
    result = subprocess.run(command, capture_output=True, text=True, check=False)
    return result.stdout


def ioreg_values() -> dict[str, str]:
    output = run(["ioreg", "-r", "-c", "AppleSmartBattery", "-w0"])
    values = {}
    for line in output.splitlines():
        match = re.search(r'"([^"]+)"\s*=\s*(.+?)\s*$', line)
        if match:
            values[match.group(1)] = match.group(2).rstrip(",").strip()
    return values


def pmset_sections() -> dict[str, dict[str, str]]:
    output = run(["pmset", "-g", "custom"])
    sections: dict[str, dict[str, str]] = {}
    current = "Общее"
    sections[current] = {}
    for line in output.splitlines():
        if line.endswith(":") and not line.startswith(" "):
            current = line[:-1]
            sections[current] = {}
            continue
        fields = line.split()
        if len(fields) >= 2:
            sections[current][fields[0]] = " ".join(fields[1:])
    return sections


def thermal() -> dict[str, str]:
    output = run(["pmset", "-g", "therm"])
    values = {}
    for line in output.splitlines():
        match = re.match(r"\s*([A-Za-z0-9_]+)\s*=\s*(.+)", line)
        if match:
            values[match.group(1)] = match.group(2).strip()
    return values


def main() -> int:
    parser = argparse.ArgumentParser(description="Отчёт по питанию и батарее")
    parser.add_argument("--json", type=Path)
    args = parser.parse_args()

    battery_text = run(["pmset", "-g", "batt"]).strip()
    values = ioreg_values()
    sections = pmset_sections()
    heat = thermal()

    def number(key: str) -> int:
        try:
            return int(values.get(key, "0"))
        except ValueError:
            return 0

    design = number("DesignCapacity")
    maximum = number("MaxCapacity")
    health = round(maximum / design * 100, 1) if design else None
    raw_temperature = number("Temperature")
    celsius = round(raw_temperature / 10 - 273.15, 1) if raw_temperature > 1000 else None

    report = {
        "battery_text": battery_text,
        "ioreg": {
            "cycle_count": number("CycleCount"),
            "design_capacity": design,
            "max_capacity": maximum,
            "health_percent": health,
            "temperature_c": celsius,
            "external_connected": values.get("ExternalConnected", ""),
            "charging": values.get("IsCharging", ""),
            "fully_charged": values.get("FullyCharged", ""),
        },
        "pmset": sections,
        "thermal": heat,
    }

    if args.json:
        args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

    print("Батарея:")
    print(f"  {battery_text or 'данные недоступны'}")
    print(f"  циклов: {report['ioreg']['cycle_count']}")
    if health is not None:
        print(f"  здоровье: {health}% ({maximum} из {design} мАч)")
    if celsius is not None:
        print(f"  температура: {celsius} C")
    print(f"  внешнее питание: {report['ioreg']['external_connected'] or 'неизвестно'}")
    print(f"  зарядка: {report['ioreg']['charging'] or 'неизвестно'}")

    print("\nНастройки pmset:")
    for section, values in sections.items():
        print(f"  {section}:")
        for key in ("sleep", "displaysleep", "hibernatemode", "standby", "powernap", "womp", "lidwake"):
            if key in values:
                print(f"    {key}: {values[key]}")

    print("\nТепловые лимиты:")
    if heat:
        for key, value in heat.items():
            print(f"  {key}: {value}")
    else:
        print("  данные недоступны")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

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

CLI 1.0.0

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

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

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

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

Категория

macOS

Shell, Python и автоматизация macOS без лишних приложений.