Lesson · Standard Data Formats
Running External Programs with subprocess
64 min readRunning External Programs with subprocess
`subprocess` launches external programs with explicit arguments, streams, exit codes, and timeouts. Passing argument lists is safer and more portable than building shell command strings.
Learning goals
- Launch a program with
subprocess.runand pass its arguments as a list. - Capture stdout and stderr, and explain when the captured data is bytes and when it is text.
- Read
result.returncodeand choose betweencheck=Trueand checking the status yourself. - Bound a child process with
timeoutand say what exception fires. - Explain why an argument list avoids shell injection while
shell=Truereintroduces it.
Mental model
The call builds a process, waits for it, and returns the outcome as one object: the arguments, the exit status, and any captured output. Everything the caller needs to react to sits on that result, so the design questions are what to capture, what status counts as failure, and what upper bound to put on the wait.
Mental model
read it top to bottom
subprocess.run([program, arg1, arg2], capture_output=True, text=True) ↓ child process runs to completion CompletedProcess(args, returncode, stdout, stderr) ↓ check=True: non-zero returncode → CalledProcessError
Core idea
subprocess is a boundary between your program and another program, and the argument list is the interface: a list bypasses the shell entirely, so each element reaches the child unchanged, while shell=True reinterprets a string with the full power of the shell. Capture and check deliberately: exit codes are the only reliable success signal, output arrives as bytes unless you ask for text, and a timeout is the only thing standing between your program and a child that never returns.
subprocess.run
subprocess.run(args, ...) executes a child program, waits for it to finish, and returns a CompletedProcess with args, returncode, stdout, and stderr. It is the default choice when a single program must run to completion before your code continues; Popen is for streaming or concurrent interaction.
Argument lists
Passing the program and its arguments as a list keeps each element separate: ["git", "log", "--oneline"] reaches the child without shell parsing, so spaces and special characters in one argument cannot split it into more arguments or commands. A single string works only in narrow cases and behaves differently across platforms, so the list form is the portable one.
Capturing output
By default the child inherits your streams; capture_output=True connects both stdout and stderr to pipes and returns their contents on result.stdout and result.stderr after the process exits. Captured output is held in memory until the call returns, so it suits modest amounts of data rather than streaming producers.
Text mode
text=True decodes captured output to str and encodes input= on the way in, using the locale encoding unless encoding= is given. Without it, pipes carry bytes, which keeps arbitrary binary output intact; the flag changes only this translation, not how the child runs.
Exit codes
A process's exit code is its success signal: by convention 0 means success and any other value means some failure the child defined. result.returncode exposes it, and on POSIX a process killed by a signal reports a negative code, so checking != 0 is safer than comparing against one expected failure value.
check=True
check=True turns a non-zero exit code into a CalledProcessError raised at the call site, with returncode, cmd, and captured output attached. It converts the did-it-work decision into an exception at the boundary, instead of code that forgets to look at returncode.
Timeouts
Timeouts places an upper bound on waiting. A timeout does not automatically undo external side effects, so design cancellation and cleanup around the resource being used.
Environment handling
The child inherits a copy of the parent's environment, or exactly what you pass via env= (the argument replaces the environment entirely, with no merging). Pass env when the child must see a specific configuration, and remember values must be strings; for targeted changes, copy os.environ and update the keys you need.
Shell invocation risks
shell=True runs the command through the system shell, so pipes, globbing, and substitution come into play and any untrusted text in the command line becomes shell code. Prefer a direct argument list; when the shell is genuinely needed, keep user input out of the string or pass values through a mechanism the shell cannot reinterpret.
Avoiding command injection
Command injection occurs when untrusted data becomes shell or command syntax. Pass argument arrays directly to subprocess APIs and avoid a shell unless shell features are genuinely required.
Walkthrough
- The argument list starts with
sys.executable, the path to the interpreter running this script, so the child is a Python process even whenpythonis not on PATH;-ctells it to execute the next string as code. "print(6 * 7)"is one list element and reaches the child unchanged because no shell parses it; the child prints42to its stdout.capture_output=Truepipes both streams back,text=Truedecodes them,check=Trueraises if the child exits non-zero, andtimeout=5kills the child if it runs longer, raisingTimeoutExpired.- Predict before running: the output
42, then what happens when the-cstring is replaced by"raise SystemExit(3)"withcheck=True.
Experiments to try
- Rerun with
check=Falseon a child that exits 3 and printresult.returncode; compare with the raisedCalledProcessErrorversion and its.returncode. - Remove
text=Trueand printresult.stdoutand its type; then decode it explicitly with.decode(). - Replace the list with
["python", "-c", "print(6 * 7)"]and see whether it still works (PATH dependence); then tryshell=Truewith the equivalent string and note the tradeoff. - Set
timeout=0.05on a child that sleeps (-c "import time; time.sleep(0.2)") and catchsubprocess.TimeoutExpired.
Common mistakes
- Passing user input into a
shell=Truecommand string: the shell reinterprets it as syntax, so a semicolon or backtick in the data becomes a new command; argument lists without the shell keep data as data. - Ignoring
returncodewhencheck=Trueis absent: a failing child, such as a missing file or a bad flag, looks like success, and the real error surfaces later or not at all. - Assuming captured output is text: without
text=Truethe pipe yieldsbytes, so a substring check like"42" in result.stdoutisFalseand prints showb"42\n". - Forgetting a timeout, or treating it as a cleanup tool: without one a hung child hangs the parent, and with one
TimeoutExpiredreports the kill while side effects the child already caused (partial files, consumed messages) remain.
Practice: Easy
- Run
[sys.executable, "-c", "print(6 * 7)"]three ways: default,capture_output=True, and withtext=True; record the type and value of the output each time. - Run a command that exits non-zero and print
result.returncode; then setcheck=Trueand capture theCalledProcessError. - Swap
sys.executablefor"python"and record whether the script still runs; explain the result with PATH.
Practice: Medium
- Write
run_ok(args)that returns(returncode, output)without raising, andrun_or_raise(args)that usescheck=True; use each where the child fails and compare how they report it. - Pass a custom environment to a child (
env={"PATH": os.environ["PATH"], "APP_MODE": "test"}) running a Python snippet that readsAPP_MODE; explain why the child cannot see other parent variables. - Capture stderr separately from stdout with a child that writes to both; describe which variable holds which text.
Practice: Hard
- Build a
run_many(commands, timeout)helper that runs commands sequentially, collects per-command status, and stops or continues per a policy; define the return shape and test it with one failing and one passing command. - Design a timeout-safe wrapper: on
TimeoutExpired, decide what cleanup is possible for a child with open files, and document why killing the process is not a rollback. - Compare two ways to feed data to a child (an argument versus stdin via
input=); choose one for a 1 MB payload and explain the limits of passing large data as command-line arguments.
Lesson checklist
- I can run a child process with an argument list and explain why no shell is involved.
- I can capture output as bytes or text and say which flag changes that.
- I can react to exit codes with
check=Trueor by readingreturncode. - I can bound a command with a timeout and describe what it does and does not undo.
Remember
`subprocess.run` crosses the process boundary with a list of arguments, a captured result, and an exit code that is the child's only reliable success signal. Keep the boundary sharp: lists instead of shell strings, `text=True` only when output is text, `check=True` when failure should raise, and a timeout whenever a child could hang; remember that killing a process never rolls back what it already did.
Interview angles
What is the main purpose of **subprocess.run**?+
subprocess.run executes one child program, waits for it to finish, and returns a CompletedProcess holding args, returncode, stdout, and stderr. It is the straight-line tool for run-to-completion commands; Popen is for streaming or concurrent interaction.
What should you pay attention to when using **Argument lists**?+
A list keeps each argument separate, so no shell parses the text: spaces and metacharacters in one element stay in that element. Building one command string reopens quoting and injection problems that the list form never had.
How does **Capturing output** fit into this lesson?+
capture_output=True pipes the child's stdout and stderr back into the result object, as bytes unless text=True is also set. The data waits in memory until the process exits, which is fine for small output and wrong for long-running producers.
Why can `timeout=5` not leave the system in its pre-command state after it fires?+
The timeout kills the child, but anything the child already did (a partially written file, a started deployment, a consumed message) is not undone; the timeout bounds waiting, not side effects.