import subprocess from typing import Iterator def stream_instance_logs(name: str, *, lines: int = 200, follow: bool = True) -> Iterator[str]: command = [ "journalctl", "--user", "-u", f"l4d2@{name}.service", "-n", str(lines), "-o", "cat", ] if follow: command.append("-f") proc = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, ) try: if proc.stdout is None: return for raw in iter(proc.stdout.readline, ""): yield raw.rstrip("\n") finally: if proc.poll() is None: proc.terminate() proc.wait(timeout=2)