#!/usr/bin/env python3 """Процессы, память и swap в 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 process_table(sort_flag: str, limit: int) -> list[dict]: output = run(["ps", "-Ao", "pid,ppid,user,%cpu,%mem,rss,etime,comm", sort_flag]) rows = [] for line in output.splitlines()[1:]: fields = line.split(None, 7) if len(fields) != 8: continue rows.append( { "pid": fields[0], "ppid": fields[1], "user": fields[2], "cpu": fields[3], "mem": fields[4], "rss_kb": fields[5], "etime": fields[6], "command": fields[7], } ) if len(rows) >= limit: break return rows def memory() -> dict: vm_stat = run(["vm_stat"]) page_size = 4096 match = re.search(r"page size of (\d+) bytes", vm_stat) if match: page_size = int(match.group(1)) pages = {} for line in vm_stat.splitlines(): item = re.match(r"([^:]+):\s+(\d+)\.", line) if item: pages[item.group(1).strip()] = int(item.group(2)) total = 0 try: total = int(run(["sysctl", "-n", "hw.memsize"]).strip()) except ValueError: pass active = pages.get("Pages active", 0) wired = pages.get("Pages wired down", 0) compressed = pages.get("Pages occupied by compressor", 0) free = pages.get("Pages free", 0) inactive = pages.get("Pages inactive", 0) speculative = pages.get("Pages speculative", 0) return { "page_size": page_size, "total_bytes": total, "used_bytes": (active + wired + compressed) * page_size, "available_bytes": (free + inactive + speculative) * page_size, "swap": run(["sysctl", "-n", "vm.swapusage"]).strip(), "pages": pages, } def main() -> int: parser = argparse.ArgumentParser(description="Процессы и память macOS") parser.add_argument("--limit", type=int, default=10) parser.add_argument("--json", type=Path) args = parser.parse_args() if args.limit < 1: parser.error("--limit должен быть положительным") by_cpu = process_table("-r", args.limit) by_memory = process_table("-m", args.limit) mem = memory() report = {"by_cpu": by_cpu, "by_memory": by_memory, "memory": mem} if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print("Топ по CPU:") for row in by_cpu: print(f" {row['cpu']:>5}% pid {row['pid']:<7} {row['command']}") print("\nТоп по памяти:") for row in by_memory: rss_mb = int(row["rss_kb"]) / 1024 print(f" {rss_mb:>7.1f} МБ pid {row['pid']:<7} {row['command']}") total_gb = mem["total_bytes"] / 1024 ** 3 used_gb = mem["used_bytes"] / 1024 ** 3 available_gb = mem["available_bytes"] / 1024 ** 3 print("\nПамять:") print(f" всего: {total_gb:.1f} ГБ") print(f" занято примерно: {used_gb:.1f} ГБ") print(f" доступно примерно: {available_gb:.1f} ГБ") print(f" swap: {mem['swap'] or 'нет данных'}") return 0 if __name__ == "__main__": raise SystemExit(main())