-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
85 lines (73 loc) · 1.91 KB
/
runner.py
File metadata and controls
85 lines (73 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
Subprocess runner with live Rich output and structured result.
"""
from __future__ import annotations
import subprocess
import sys
from dataclasses import dataclass, field
from typing import Sequence
from rich.console import Console
console = Console()
@dataclass
class RunResult:
cmd: list[str]
returncode: int
stdout: str
stderr: str
@property
def ok(self) -> bool:
return self.returncode == 0
@property
def output(self) -> str:
return (self.stdout + "\n" + self.stderr).strip()
def run(
cmd: Sequence[str],
cwd: str | None = None,
env: dict | None = None,
live: bool = True,
timeout: int = 600,
) -> RunResult:
"""
Run a subprocess. When live=True, stream stdout/stderr to terminal
in real time while also capturing output.
"""
import os
merged_env = {**os.environ, **(env or {})}
if live:
proc = subprocess.Popen(
list(cmd),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=cwd,
env=merged_env,
text=True,
bufsize=1,
)
captured: list[str] = []
assert proc.stdout is not None
for line in proc.stdout:
captured.append(line)
console.print(line, end="", markup=False, highlight=False)
proc.wait(timeout=timeout)
combined = "".join(captured)
return RunResult(
cmd=list(cmd),
returncode=proc.returncode,
stdout=combined,
stderr="",
)
else:
result = subprocess.run(
list(cmd),
capture_output=True,
text=True,
cwd=cwd,
env=merged_env,
timeout=timeout,
)
return RunResult(
cmd=list(cmd),
returncode=result.returncode,
stdout=result.stdout,
stderr=result.stderr,
)