-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
65 lines (54 loc) · 1.63 KB
/
Copy pathrunner.py
File metadata and controls
65 lines (54 loc) · 1.63 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
from __future__ import annotations
import os
import shlex
import subprocess
from dataclasses import dataclass
from typing import List, Optional
@dataclass(frozen=True)
class RunResult:
command: str
exit_code: int
stdout: str
stderr: str
interrupted: bool = False
def _stringify_command(argv: List[str]) -> str:
return " ".join(shlex.quote(a) for a in argv)
def run_command(argv: List[str], *, timeout_s: Optional[int] = None) -> RunResult:
"""Run a command and capture stdout/stderr.
- Uses text mode.
- Normalizes common shell failures (e.g. command not found).
- Returns exit code + output. Marks interrupted on KeyboardInterrupt.
"""
cmd_str = _stringify_command(argv)
try:
cp = subprocess.run(
argv,
text=True,
capture_output=True,
timeout=timeout_s,
env=os.environ.copy(),
)
return RunResult(
command=cmd_str,
exit_code=int(cp.returncode),
stdout=cp.stdout or "",
stderr=cp.stderr or "",
interrupted=False,
)
except FileNotFoundError:
# ✅ Normalize "command not found"
return RunResult(
command=cmd_str,
exit_code=127, # POSIX convention
stdout="",
stderr=f"{argv[0]}: command not found",
interrupted=False,
)
except KeyboardInterrupt:
return RunResult(
command=cmd_str,
exit_code=130, # conventional for SIGINT
stdout="",
stderr="Command interrupted (SIGINT).",
interrupted=True,
)