Skip to content

Commit

Permalink
Add /proc technique
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagocoutinho committed Oct 7, 2024
1 parent c2b4df5 commit 4868df5
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
2 changes: 1 addition & 1 deletion linuxpy/mounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import functools
from pathlib import Path

from .proc import PROC_PATH
from .types import Generator, NamedTuple, Optional

PROC_PATH = Path("/proc")
MOUNTS_PATH: Path = PROC_PATH / "mounts"


Expand Down
50 changes: 50 additions & 0 deletions linuxpy/proc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from pathlib import Path

from linuxpy.util import try_numeric

PROC_PATH = Path("/proc")

CPU_INFO_PATH: Path = PROC_PATH / "cpuinfo"
MEM_INFO_PATH: Path = PROC_PATH / "meminfo"
MODULES_PATH: Path = PROC_PATH / "modules"


def iter_cpu_info():
data = CPU_INFO_PATH.read_text()
for cpu in data.split("\n\n"):
info = {}
for line in cpu.splitlines():
key, value = map(str.strip, line.split(":", 1))
if "flags" in key or key == "bugs":
value = value.split()
else:
value = try_numeric(value)
info[key] = value
yield info


def iter_mem_info():
data = MEM_INFO_PATH.read_text()
for line in data.splitlines():
key, value = map(str.strip, line.split(":", 1))
if value.endswith(" kB"):
value = try_numeric(value[:-3]) * 1024
else:
value = try_numeric(value)
yield key, value


def iter_modules():
data = MODULES_PATH.read_text()
for line in data.splitlines():
fields = line.split()
mod = {
"name": fields[0],
"size": int(fields[1]),
"use_count": int(fields[2]),
"dependencies": [] if fields[3] == "-" else [dep for dep in fields[3].split(",") if dep],
}
if len(fields) > 5:
mod["state"] = fields[4]
mod["offset"] = int(fields[5], 16)
yield mod
23 changes: 23 additions & 0 deletions linuxpy/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import asyncio
import contextlib
import functools
import random
import selectors
import string
Expand Down Expand Up @@ -78,6 +79,28 @@ def to_fd(fd: FDLike):
return fd


int16 = functools.partial(int, base=16)


def try_numeric(text: str):
"""
Try to translate given text into int, int base 16 or float.
Returns the orig and return the original text if it fails.
Args:
text (str): text to be translated
Returns:
int, float or str: The converted text
"""
for func in (int, int16, float):
try:
return func(text)
except ValueError:
pass
return text


@contextlib.contextmanager
def add_reader_asyncio(fd: FDLike, callback: Callable, *args, loop: Optional[asyncio.AbstractEventLoop] = None):
"""Add reader during the context and remove it after"""
Expand Down

0 comments on commit 4868df5

Please sign in to comment.