#!/usr/bin/env python3 """Топ процессов Linux по CPU и памяти из /proc.""" from __future__ import annotations import argparse import json import os import pwd import time from dataclasses import asdict, dataclass from pathlib import Path CLK_TCK = os.sysconf("SC_CLK_TCK") @dataclass class ProcessRow: pid: int user: str cpu_percent: float memory_percent: float rss: int command: str def total_cpu_ticks() -> int: line = Path("/proc/stat").read_text(encoding="utf-8").splitlines()[0] values = [int(item) for item in line.split()[1:9]] return sum(values) def sample_processes() -> dict[int, int]: samples: dict[int, int] = {} for entry in os.listdir("/proc"): if not entry.isdigit(): continue try: stat = Path("/proc") / entry / "stat" text = stat.read_text(encoding="utf-8", errors="replace") except OSError: continue right = text.rfind(")") if right < 0: continue fields = text[right + 2:].split() if len(fields) < 22: continue try: samples[int(entry)] = int(fields[11]) + int(fields[12]) except ValueError: continue return samples def read_status(pid: int) -> tuple[int, str, int]: try: text = (Path("/proc") / str(pid) / "status").read_text(encoding="utf-8", errors="replace") except OSError: return 0, "?", 0 uid = 0 name = "?" rss = 0 for line in text.splitlines(): if line.startswith("Uid:"): parts = line.split() if len(parts) > 1: uid = int(parts[1]) elif line.startswith("Name:"): name = line.split(":", 1)[1].strip() elif line.startswith("VmRSS:"): parts = line.split() if len(parts) > 1: rss = int(parts[1]) * 1024 return uid, name, rss def command_line(pid: int, fallback: str) -> str: try: raw = (Path("/proc") / str(pid) / "cmdline").read_bytes() except OSError: return f"[{fallback}]" text = raw.replace(b"\x00", b" ").decode("utf-8", errors="replace").strip() return text if text else f"[{fallback}]" def user_name(uid: int) -> str: try: return pwd.getpwuid(uid).pw_name except KeyError: return str(uid) def human(value: int) -> str: size = float(value) for unit in ("B", "KiB", "MiB", "GiB", "TiB"): if size < 1024 or unit == "TiB": return f"{size:.1f} {unit}" size /= 1024 return f"{value} B" def main() -> int: parser = argparse.ArgumentParser(description="Топ процессов Linux") parser.add_argument("--interval", type=float, default=1.0, help="Интервал измерения в секундах") parser.add_argument("--top", type=int, default=15, help="Сколько процессов показать") parser.add_argument("--sort", choices=("cpu", "mem"), default="cpu", help="Сортировка") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() if args.interval < 0.1: parser.error("--interval должен быть не меньше 0.1") if args.top < 1: parser.error("--top должен быть положительным") cpu_count = os.cpu_count() or 1 total1 = total_cpu_ticks() processes1 = sample_processes() time.sleep(args.interval) total2 = total_cpu_ticks() processes2 = sample_processes() delta_total = max(total2 - total1, 1) meminfo = {} for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines(): key, value = line.split(":", 1) parts = value.split() if parts: meminfo[key] = int(parts[0]) * 1024 mem_total = max(meminfo.get("MemTotal", 0), 1) rows: list[ProcessRow] = [] for pid, ticks2 in processes2.items(): if pid not in processes1: continue delta = max(ticks2 - processes1[pid], 0) cpu_percent = delta / delta_total * cpu_count * 100.0 uid, name, rss = read_status(pid) rows.append( ProcessRow( pid=pid, user=user_name(uid), cpu_percent=cpu_percent, memory_percent=rss / mem_total * 100.0, rss=rss, command=command_line(pid, name)[:120], ) ) key = (lambda item: item.cpu_percent) if args.sort == "cpu" else (lambda item: item.rss) rows.sort(key=key, reverse=True) rows = rows[:args.top] load1, load5, load15 = Path("/proc/loadavg").read_text(encoding="utf-8").split()[:3] print(f"CPU: {cpu_count} ядер, load average: {load1} {load5} {load15}") print(f"Интервал: {args.interval:.1f} с, сортировка: {args.sort}") print(f"{'PID':>7} {'ПОЛЬЗОВАТЕЛЬ':<14} {'CPU%':>6} {'MEM%':>6} {'RSS':>10} КОМАНДА") print("-" * 120) for row in rows: print(f"{row.pid:>7} {row.user:<14} {row.cpu_percent:>6.1f} {row.memory_percent:>6.1f} {human(row.rss):>10} {row.command}") if args.json: args.json.write_text( json.dumps( { "cpu_count": cpu_count, "load": [load1, load5, load15], "interval": args.interval, "processes": [asdict(row) for row in rows], }, ensure_ascii=False, indent=2, ) + "\n", encoding="utf-8", ) print(f"\nJSON сохранён: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())