Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you stream a long-running command's output line by line?

AdvancedConceptOS, filesystem, subprocess & CLIs
Answer

Use Popen and iterate stdout, so logs appear live instead of after the process ends:

with subprocess.Popen(["terraform", "apply", "-auto-approve"], stdout=subprocess.PIPE,
                      stderr=subprocess.STDOUT, text=True, bufsize=1) as p:
    for line in p.stdout:
        log.info("tf: %s", line.rstrip())
if p.returncode != 0:
    raise RuntimeError(f"terraform exited {p.returncode}")

Merging stderr into stdout avoids the deadlock you get when reading one pipe while the other fills its buffer.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs