-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path_subprocess.py
More file actions
36 lines (27 loc) · 1.01 KB
/
_subprocess.py
File metadata and controls
36 lines (27 loc) · 1.01 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
"""Subprocess invocation utilities."""
from __future__ import annotations
import subprocess
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
class SubprocessFailedError(Exception):
pass
def call_subprocess(args: list[str], *, cwd: Path | None = None) -> str:
"""Run a subprocess and return its stdout, raising SubprocessFailedError on failure."""
try:
process = subprocess.run( # noqa: S603
args, check=True, capture_output=True, cwd=cwd.as_posix() if cwd else None
)
return process.stdout.decode()
except subprocess.CalledProcessError as err:
bmsg_stderr: bytes = err.stderr
bmsg_stdout: bytes = err.stdout
stderr = bmsg_stderr.decode()
stdout = bmsg_stdout.decode()
msg = "Failed to run subprocess:"
msg += f"\n {' '.join(args)}"
if stderr:
msg += f"\n{stderr=}"
if stdout:
msg += f"\n{stdout=}"
raise SubprocessFailedError(msg) from None