Courses/Systems Concepts (read-only)

๐Ÿง  Systems Concepts (read-only)

subprocess โ€” streaming & pipes

Read output line by line; pipe commands together.

For long-running commands, don't wait for the whole stdout โ€” stream it.

import subprocess

# Stream lines as they appear
p = subprocess.Popen(
    ["ping", "-c", "3", "example.com"],
    stdout=subprocess.PIPE, text=True, bufsize=1,
)
for line in p.stdout:
    print("โ€บ", line.rstrip())
p.wait()

# Pipe one process into another: ls | grep py
ls   = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
grep = subprocess.Popen(["grep", "py"], stdin=ls.stdout, stdout=subprocess.PIPE, text=True)
ls.stdout.close()             # let ls receive SIGPIPE if grep exits
out, _ = grep.communicate()
print(out)

**Safety**

  • Pass a **list** of args, not a shell string โ€” no injection.
  • Set a timeout= on .communicate() to avoid hangs.
  • Use shutil.which("cmd") to confirm a binary is on PATH before Popen.

> ๐Ÿงช Concept-only โ€” no subprocesses in the browser.

Concept lesson

This topic relies on OS features the in-browser Python sandbox can't run (threads, subprocesses, sockets). Read the examples here, then try them in real CPython on your machine.

Sign in to track your progress across lessons.