Files
myfirstprogram/utils/mac_metrics.py
T
2025-10-05 23:16:19 +03:00

67 lines
2.0 KiB
Python

import asyncio
import os
async def get_macbook_battery_level():
process = await asyncio.create_subprocess_exec(
"pmset", "-g", "batt",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
raise RuntimeError(f"Ошибка при выполнении pmset: {stderr.decode().strip()}")
output = stdout.decode().strip()
for part in output.splitlines():
if "%" in part:
percent_str = part.split("\t")[-1].split(";")[0].strip()
return int(percent_str.replace("%", ""))
raise ValueError("Не удалось определить уровень заряда")
async def get_process_usage(pid=None):
"""
Возвращает CPU, MEM% и RSS в мегабайтах для указанного процесса.
По умолчанию берёт текущий процесс (os.getpid()).
"""
if pid is None:
pid = os.getpid()
process = await asyncio.create_subprocess_exec(
"ps", "-p", str(pid), "-o", "%cpu,%mem,rss,comm",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
raise RuntimeError(f"Ошибка ps: {stderr.decode().strip()}")
lines = stdout.decode().strip().splitlines()
if len(lines) < 2:
return None
cpu, mem_percent, rss_kb, comm = lines[1].split(None, 3)
return {
"pid": pid,
"command": comm,
"cpu_percent": float(cpu),
"mem_percent": float(mem_percent),
"rss_mb": int(rss_kb) / 1024 # переводим КБ → МБ
}
async def main():
battery = await get_macbook_battery_level()
usage = await get_process_usage()
print(f"🔋 Батарея: {battery}%")
print(f"🖥 CPU: {usage['cpu_percent']}% | MEM: {usage['mem_percent']}% | RSS: {usage['rss_mb']:.2f} MB")
if __name__ == "__main__":
asyncio.run(main())