Back
+15 XP
Concept

Streaming Command Output with subprocess.Popen

`subprocess.Popen` provides low-level streaming of long-running processes. You can read lines from `proc.stdout` in real time as they are generated 🌊.

python
import subprocess

proc = subprocess.Popen(
    ["echo", "streaming line 1\nstreaming line 2"],
    stdout=subprocess.PIPE,
    text=True
)

for line in proc.stdout:
    print(f"Streamed: {line.strip()} 🌊")

proc.wait()

# 102. Streaming Command Output with subprocess.Popen `subprocess.Popen` provides low-level streaming of long-running processes. You can read lines from `proc.stdout` in real time as they are generated 🌊. ```python import subprocess proc = subprocess.Popen( ["echo", "streaming line 1\nstreaming line 2"], stdout=subprocess.PIPE, text=True ) for line in proc.stdout: print(f"Streamed: {line.strip()} 🌊") proc.wait() ``` While `subprocess.run` blocks until the program finishes, `subprocess.Popen` launches the process asynchronously in the background so you can interact with pipes! 🌊 --- ### Question When should you use `subprocess.Popen` instead of `subprocess.run`? 🧠 - [ ] a. When you need to stream stdout/stderr in real-time or communicate with running processes 🌊 - [ ] b. Only when executing Python scripts inside virtual environments - [ ] c. When running commands on Windows without admin permissions - [ ] d. Popen is deprecated and should never be used --- ### Challenge Spawn `subprocess.Popen(['echo', 'data_chunk'], stdout=subprocess.PIPE, text=True)`. Read output with `proc.communicate()[0].strip()` and print it. 🎯 <details> <summary>Solution</summary> ```python import subprocess proc = subprocess.Popen(["echo", "data_chunk"], stdout=subprocess.PIPE, text=True) out, _ = proc.communicate() print(out.strip()) ``` </details>

Checkpoint

When should you use `subprocess.Popen` instead of `subprocess.run`? 🧠

Practice

Spawn `subprocess.Popen(['echo', 'data_chunk'], stdout=subprocess.PIPE, text=True)`. Read output with `proc.communicate()[0].strip()` and print it. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks