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.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?Intermediate