Skip to content

Tools

tools

Low-level runtime utilities: user prompts and subprocess execution.

Sections
  • User interaction: prompt helpers
  • Subprocess: wrappers around subprocess.run and shell script execution

Functions:

Name Description
ask

Ask a yes/no question via input() and return their answer.

get_exec_dir

Return the directory where the current script is located.

run

Run a subprocess command and optionally capture its output.

run_script

Run a shell script and return its output as a string.

ask

ask(prompt: str, default='y')

Ask a yes/no question via input() and return their answer.

Source code in oops/io/tools.py
def ask(prompt: str, default="y"):
    """Ask a yes/no question via input() and return their answer."""

    try:
        answer = input(prompt).strip().lower()
    except EOFError:
        answer = ""
    return answer or default

get_exec_dir

get_exec_dir()

Return the directory where the current script is located.

Source code in oops/io/tools.py
def get_exec_dir():
    """Return the directory where the current script is located."""

    return os.path.dirname(__file__)

run

run(cmd: list, check: bool = True, capture: bool = False, cwd: Optional[str] = None, name: Optional[str] = None) -> Optional[str]

Run a subprocess command and optionally capture its output.

Parameters:

Name Type Description Default

cmd

list

Command and arguments to execute.

required

check

bool

If True, raise CalledProcessError on non-zero exit. Defaults to True.

True

capture

bool

If True, capture and return stdout. Defaults to False.

False

cwd

Optional[str]

Working directory for the subprocess. Defaults to None.

None

name

Optional[str]

Label used in debug log output. Defaults to None.

None

Returns:

Type Description
Optional[str]

Captured stdout as a string if capture is True, otherwise None.

Source code in oops/io/tools.py
def run(
    cmd: list,
    check: bool = True,
    capture: bool = False,
    cwd: Optional[str] = None,
    name: Optional[str] = None,
) -> Optional[str]:
    """Run a subprocess command and optionally capture its output.

    Args:
        cmd: Command and arguments to execute.
        check: If True, raise CalledProcessError on non-zero exit. Defaults to True.
        capture: If True, capture and return stdout. Defaults to False.
        cwd: Working directory for the subprocess. Defaults to None.
        name: Label used in debug log output. Defaults to None.

    Returns:
        Captured stdout as a string if capture is True, otherwise None.
    """
    kwargs: dict = dict(text=True, cwd=cwd)
    if capture:
        # assign explicitly to avoid static type checkers inferring incompatible dict value types
        kwargs["stdout"] = subprocess.PIPE
        kwargs["stderr"] = subprocess.PIPE

    logging.debug(f"[{name or 'run'}] {' '.join(cmd)}")

    res = subprocess.run(cmd, check=check, **kwargs)
    return res.stdout if capture else None

run_script

run_script(filepath: str, *args: str) -> str

Run a shell script and return its output as a string.

Source code in oops/io/tools.py
def run_script(filepath: str, *args: str) -> str:
    """Run a shell script and return its output as a string."""

    path = os.path.join(get_exec_dir(), filepath)
    logging.debug(f"[script] Running script from {path}")

    if not os.path.exists(path):
        raise ScriptNotFound()

    result = subprocess.run([path, *args], capture_output=True, text=True, check=True)
    return result.stdout