Files
claude-config/bin/loop_claude/memory.py
T

34 lines
1.1 KiB
Python

import dataclasses
import pathlib
import re
MEMINFO = pathlib.Path("/proc/meminfo")
# A worker starts only while this share of the machine's memory is available; the human chose it, as no standard sets one.
ROOM_SHARE = 0.25
@dataclasses.dataclass(frozen=True)
class Memory:
"""The machine's memory, in kB as /proc/meminfo counts it: what a new process can have without swapping, and all of it."""
available: int
total: int
def has_room(self) -> bool:
return self.available >= ROOM_SHARE * self.total
def parsed(meminfo: str) -> Memory | None:
"""The memory a /proc/meminfo text states; None where it lacks MemAvailable or MemTotal."""
fields = dict(re.findall(r"^(MemAvailable|MemTotal):\s+(\d+) kB$", meminfo, re.MULTILINE))
if len(fields) != 2:
return None
return Memory(available=int(fields["MemAvailable"]), total=int(fields["MemTotal"]))
def read_memory(meminfo: pathlib.Path = MEMINFO) -> Memory | None:
"""The machine's memory; None where meminfo cannot be read, as off Linux."""
try:
return parsed(meminfo.read_text())
except OSError:
return None