Run a subprocess with a hard timeout
Python
import subprocess
import sys
from dataclasses import dataclass
@dataclass
class Result:
ok: bool
output: str
error: str
returncode: int | None
def run(command: list[str], timeout: float = 10.0) -> Result:
"""Run a command with a hard timeout and capture its output safely."""
try:
proc = subprocess.run(
command,
capture_output=True,
text=True,
timeout=timeout,
check=False, # report the exit code instead of raising
)
except subprocess.TimeoutExpired:
return Result(False, "", f"timed out after {timeout}s", None)
except FileNotFoundError as exc:
return Result(False, "", str(exc), None)
return Result(proc.returncode == 0, proc.stdout, proc.stderr, proc.returncode)
if __name__ == "__main__":
print(run([sys.executable, "--version"], timeout=5))
print(run(["definitely-not-a-command"], timeout=1))