rwx/rwx/ps/__init__.py
Marc Beninca 020aaa0b9a
All checks were successful
/ job (push) Successful in 1m12s
refactor(history): commit development branch
new development branch from root commit
2025-02-10 21:54:51 +01:00

85 lines
2.1 KiB
Python

"""Handle processes."""
from __future__ import annotations
import subprocess
from rwx import Object, txt
class Command(Object):
"""Command to run."""
def __init__(self, *arguments: str | tuple[str, ...]) -> None:
"""Set raw & flat arguments.
:param *arguments: single argument or grouped ones
:type *arguments: str | tuple[str, ...]
"""
self.raw = arguments
self.flat: list[str] = []
def get_tuples_args(*items: str | tuple[str, ...]) -> list[str]:
"""Turn arguments tuples into an arguments list.
:param *items: single item or grouped ones
:type *items: str | tuple[str, ...]
:rtype: list[str]
"""
args: list[str] = []
for item in items:
match item:
case str():
args.append(item)
case tuple():
args.extend(item)
return args
def run(*items: str | tuple[str, ...]) -> subprocess.CompletedProcess:
"""Run from a list of arguments tuples.
:param *items: single item or grouped ones
:type *items: str | tuple[str, ...]
:rtype: subprocess.CompletedProcess
"""
return subprocess.run(
get_tuples_args(*items),
capture_output=False,
check=True,
)
def run_line(*items: str | tuple[str, ...], charset: str = txt.CHARSET) -> str:
"""Run and return output line.
:param *items: single item or grouped ones
:type *items: str | tuple[str, ...]
:param charset: charset to use for decoding binary output
:type charset: str
:rtype: str
"""
line, *_ = run_lines(*items, charset=charset)
return line
def run_lines(
*items: str | tuple[str, ...],
charset: str = txt.CHARSET,
) -> list[str]:
"""Run and return output lines.
:param *items: single item or grouped ones
:type *items: str | tuple[str, ...]
:param charset: charset to use for decoding binary output
:type charset: str
:rtype: list[str]
"""
process = subprocess.run(
get_tuples_args(*items),
capture_output=True,
check=True,
)
string = process.stdout.decode(charset)
return string.rstrip().splitlines()