46 lines
1.1 KiB
Python
46 lines
1.1 KiB
Python
"""Command execution with streaming output."""
|
|
|
|
import subprocess
|
|
|
|
from flow.core.console import ConsoleLogger
|
|
|
|
|
|
def run_command(
|
|
command: str,
|
|
console: ConsoleLogger,
|
|
*,
|
|
check: bool = True,
|
|
shell: bool = True,
|
|
capture: bool = False,
|
|
) -> subprocess.CompletedProcess:
|
|
"""Run a command with real-time streamed output."""
|
|
console.step_command(command)
|
|
|
|
process = subprocess.Popen(
|
|
command,
|
|
shell=shell,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
universal_newlines=True,
|
|
bufsize=1,
|
|
)
|
|
|
|
output_lines = []
|
|
for line in process.stdout:
|
|
line = line.rstrip()
|
|
if line:
|
|
if not capture:
|
|
console.step_output(line)
|
|
output_lines.append(line)
|
|
|
|
process.wait()
|
|
|
|
if check and process.returncode != 0:
|
|
raise RuntimeError(
|
|
f"Command failed (exit {process.returncode}): {command}"
|
|
)
|
|
|
|
return subprocess.CompletedProcess(
|
|
command, process.returncode, stdout="\n".join(output_lines), stderr=""
|
|
)
|