Skip to content

tool_run

tool_run #

run_tool — subprocess.run for a recipe: the child's output streams into the log.

The command is a log scope; both of the child's streams are pumped, as they arrive, into the live directory's exec.log and into one tail entry beneath the scope holding the last lines, so a page or terminal shows what the tool is saying. Only a capturing caller's streams are also buffered. With no log to write the call is a plain subprocess.run under the same scope.

run_tool(argv, *, cwd, env, timeout, check, capture_output, log) #

Run argv in cwd the way subprocess.run does, streaming its output to log.

Parameters:

Name Type Description Default
argv Sequence[str | PathLike[str]]

The command line.

required
cwd PathLike[str]

The working directory.

required
env Mapping[str, str] | None

The child's environment, or the parent's when None.

required
timeout float | None

Seconds before the child is killed.

required
check bool

Whether a non-zero exit raises.

required
capture_output bool

Whether stdout and stderr come back on the result.

required
log Path | None

The exec.log the output is appended to, or None to log nothing.

required

Raises:

Type Description
CalledProcessError

If check and the child exits non-zero.

TimeoutExpired

If the child outlives timeout.

Source code in capturegraph-lib/capturegraph/scratch/values/tool_run.py
def run_tool(
    argv: Sequence[str | os.PathLike[str]],
    *,
    cwd: os.PathLike[str],
    env: Mapping[str, str] | None,
    timeout: float | None,
    check: bool,
    capture_output: bool,
    log: Path | None,
) -> subprocess.CompletedProcess[bytes]:
    """Run ``argv`` in ``cwd`` the way ``subprocess.run`` does, streaming its output to ``log``.

    Args:
        argv: The command line.
        cwd: The working directory.
        env: The child's environment, or the parent's when ``None``.
        timeout: Seconds before the child is killed.
        check: Whether a non-zero exit raises.
        capture_output: Whether stdout and stderr come back on the result.
        log: The ``exec.log`` the output is appended to, or ``None`` to log nothing.

    Raises:
        subprocess.CalledProcessError: If ``check`` and the child exits non-zero.
        subprocess.TimeoutExpired: If the child outlives ``timeout``.
    """
    command = [os.fspath(argument) for argument in argv]
    with info(f"$ {shlex.join(command)}", kind="command"):
        if log is None:
            return subprocess.run(
                command,
                cwd=cwd,
                env=env,
                timeout=timeout,
                check=check,
                capture_output=capture_output,
            )
        with open(log, "ab") as sink:
            sink.write(f"$ {shlex.join(command)}\n".encode())
            sink.flush()
            return _run_logged(command, sink, cwd, env, timeout, check, capture_output)