CommonAutoRearsh/engine/runner.py

39 lines
1.0 KiB
Python

from __future__ import annotations
import subprocess
import time
from pathlib import Path
from engine.models import RunResult
def run_command(command: str, cwd: Path, timeout_seconds: int) -> RunResult:
start = time.perf_counter()
try:
completed = subprocess.run(
command,
cwd=str(cwd),
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
timeout=timeout_seconds,
check=False,
)
exit_code = completed.returncode
stdout = completed.stdout
stderr = completed.stderr
except subprocess.TimeoutExpired as exc:
exit_code = 124
stdout = exc.stdout or exc.output or ""
stderr = exc.stderr or f"command timed out after {timeout_seconds} seconds"
runtime_seconds = time.perf_counter() - start
return RunResult(
command=command,
cwd=cwd,
exit_code=exit_code,
runtime_seconds=runtime_seconds,
stdout=stdout,
stderr=stderr,
)