Python

Python subprocess — run, Capture, check, and Timeout

A Python program often needs one job done by another program: run a tool, collect what it prints, and react when it fails. The subprocess module does that job without a shell in between. The run function starts a child, waits for it to finish, and hands back a result that carries the exit code and any captured output. This guide runs small Python children so every output is exact, passes arguments the safe way, sends input, and ends with the traps that come from a missing program, a silent failure, and a child that never stops.

Written November 13, 2026 · Tested with Python 3.12.3 · 10 min read

By the end of this guide
  • The main program: run a child and read the result
  • Arguments: a list, not a shell string
  • Capture: stdout, stderr, and text mode
  • Input: sending text to a child

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

The subprocess module runs another program from Python. The parent program builds a command as a list, starts a child process, and waits. The child has its own standard output and standard error streams, its own input, and an exit code it chooses when it ends. A code of 0 means success by the usual convention, and any other code means the child reported a problem in its own way. The examples here use the current Python interpreter as the child, through sys.executable, so the child code is short, the outputs are exact, and no outside tool has to be installed first. The same run call works for any program on the system path.

The main program: run a child and read the result

The run function takes the command as a list, where the first item names the program and the rest are its arguments. With capture_output set, the child's output is collected instead of going to the parent's terminal. With text set, that output arrives as a string. Run waits until the child ends, then returns a CompletedProcess object:

Python
import subprocess, sys
result = subprocess.run([sys.executable, "-c", "print('hello from child')"], capture_output=True, text=True)
print(result.returncode)
print(result.stdout.strip())
print(repr(result.stderr))
print(type(result).__name__)

The exact output:

Output
0
hello from child
''
CompletedProcess

The returncode is 0, the captured output holds the line the child printed plus its newline, and the error stream is an empty string because the child printed nothing there. The strip call removed the trailing newline for display. Nothing in this result proves the child did the right work: it proves the child ran, ended, and reported 0. Checking the output text is a separate step, and later sections show how a non-zero code can be turned into an error instead of being read by hand each time.

Arguments: a list, not a shell string

Each list item reaches the child as one argument, even when it contains spaces. A child that reads sys.argv sees the program name first, then the arguments in order. No shell splits the text, joins it again, or treats punctuation inside an argument as an instruction:

Python
import subprocess, sys
code = "import sys; print(sys.argv[1:]); print(len(sys.argv) - 1)"
result = subprocess.run([sys.executable, "-c", code, "ana", "two words", "9"], capture_output=True, text=True)
print(result.stdout, end="")
print(result.returncode)

The exact output:

Output
['ana', 'two words', '9']
3
0

The two-word value arrived as a single argument, the count is 3, and the number 9 arrived as the string '9', because arguments are always text. Code that needs a number converts it after reading it. Passing one long string as the command instead would hand that whole string to the system as a program name, which is a common first error. The list form states each part plainly and keeps user-supplied values as data, in the same spirit as a bound parameter in a database query.

Capture: stdout, stderr, and text mode

A child has two output streams. Standard output carries the normal result, and standard error carries diagnostics. Capture collects both, apart, so the parent can read a result without error text mixed into it. Without text mode, the captured values are bytes:

Python
import subprocess, sys
code = "import sys; print('to stdout'); print('to stderr', file=sys.stderr)"
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
print(repr(result.stdout))
print(repr(result.stderr))
plain = subprocess.run([sys.executable, "-c", code], capture_output=True)
print(type(plain.stdout).__name__)

The exact output:

Output
'to stdout\n'
'to stderr\n'
bytes

Each captured string ends with the newline its print call added, which the repr form makes visible. The second run dropped text mode, so its output type is bytes and string work on it would need a decode step first. A child whose output is not captured prints straight to the parent's terminal instead, and the result object then holds None for those fields. Capture is the right choice when the parent needs to check, store, or forward the output. Leaving output uncaptured is the right choice for a long tool run whose progress a person should watch as it happens.

Input: sending text to a child

The input argument feeds text to the child's standard input, and then closes that stream so a child reading to the end can finish. A child reads that input the same way a program reads typed text, through sys.stdin:

Python
import subprocess, sys
code = "import sys; lines = sys.stdin.read().splitlines(); print(len(lines)); print(lines[0].upper())"
result = subprocess.run([sys.executable, "-c", code], input="ana\nben\n", capture_output=True, text=True)
print(result.stdout, end="")
print(result.returncode)

The exact output:

Output
2
ANA
0

The child counted two lines and uppercased the first one. The input string in the parent is an ordinary string with newline characters, written here with escapes so it stays on one line. Input pairs with text mode: in bytes mode the input must be bytes as well. A child that prompts, waits, and reads one line at a time needs a different, interactive approach; run with a fixed input string suits a child that reads a known block and ends, which covers filters, formatters, and small helper tools.

Failure: returncode and check

Run does not raise an error when a child ends with a non-zero code. It reports the code, and the parent decides what it means. Passing check=True changes that bargain: a non-zero code raises CalledProcessError, and the error object carries the code and the captured output:

Python
import subprocess, sys
code = "import sys; print('working'); sys.exit(3)"
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
print(result.returncode)
print(result.stdout.strip())
try:
    subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as error:
    print(type(error).__name__, error.returncode)
    print(error.stdout.strip())

The exact output:

Output
3
working
CalledProcessError 3
working

The first run returned normally with code 3 in the result. The second run raised, and the handler read the same code and the same captured line from the error object. Check is a good default when a failed child means the parent cannot continue, because the failure cannot be forgotten by accident. Reading returncode by hand is better when several codes each need a different response, or when a non-zero code is a normal answer, as with a search tool that reports no match by exiting 1. Either way, the code must be looked at somewhere: an unchecked child can fail in silence while the parent goes on with missing output.

Timeout: stopping a child that runs too long

The timeout argument sets a limit in seconds. When the child is still running at the limit, run kills it and raises TimeoutExpired. The error carries the limit that was hit, so a handler can log the budget that proved too small:

Python
import subprocess, sys
code = "import time; time.sleep(5)"
try:
    subprocess.run([sys.executable, "-c", code], timeout=0.2, capture_output=True, text=True)
    print("finished")
except subprocess.TimeoutExpired as error:
    print(type(error).__name__)
    print(error.timeout)
print("continued")

The exact output:

Output
TimeoutExpired
0.2
continued

The child planned to sleep for five seconds, the limit cut it off after 0.2 seconds, and the parent continued with its own work. A timeout is a guard, not a schedule: set it well above the time a healthy run needs, so a slow machine does not trip it by accident, and treat a hit as a fault to look into. Output captured before the kill may be present on the error object in bytes form even in text mode, so a handler that needs that partial output should be ready to decode it. A program with no timeout at all can wait forever on a stuck child, which is why any child whose run time is not bounded by its input deserves a limit.

Three traps: a missing program, a literal argument, and a silent failure

Trap
A program name that does not exist raises FileNotFoundError before any child starts, which is a different failure from a child that starts and exits badly. An argument that contains shell punctuation is just text in list form, so a semicolon inside a value cannot start a second command. And a child that exits 2 without check leaves the parent running unless the code is read:
Python
import subprocess, sys
try:
    subprocess.run(["veldica-no-such-program-9"], capture_output=True, text=True)
except FileNotFoundError as error:
    print(type(error).__name__)
result = subprocess.run([sys.executable, "-c", "print('a;b')"], capture_output=True, text=True)
print(result.stdout.strip())
print(result.returncode)
bad = subprocess.run([sys.executable, "-c", "import sys; sys.exit(2)"], capture_output=True, text=True)
print("unchecked", bad.returncode)

The exact output:

Output
FileNotFoundError
a;b
0
unchecked 2

The missing name raised at once. The semicolon printed as part of the child's line, with a clean exit. The last child failed with code 2, and only the printed line shows it, because nothing in that call asked for an error. These three traps share one shape: the module reports each problem in a precise place, a raised error, a result field, or an error object, and the bug is code that never looks there. A short wrapper that runs a command, checks the result, and returns the output text is worth writing once a program calls more than one child.

Which choice for which job

Job Choice Why
Run and collect output run with capture Waits, returns code and text
Arguments with spaces List form Each value stays one argument
A failure must stop work check=True Non-zero raises an error
Codes need own handling Read returncode Each code gets a response
Feed a known block input text Child reads it, then ends
A child may hang timeout Run kills it at the limit
Watch progress live No capture Output goes to the terminal

Checklist

  • Before building a command as one string, stop; build it as a list, with each argument as its own item.
  • Before trusting a result, read returncode or pass check=True; a child that ended badly still returns a result object.
  • Before parsing captured output, confirm text mode was set; without it the output is bytes.
  • Before feeding a child, set input as a string in text mode and bytes in bytes mode; the two must match.
  • Before running a child with no known time bound, set a timeout; a stuck child otherwise waits forever.
  • Before reporting a missing tool as a child failure, separate the two: a bad name raises FileNotFoundError, and a started child reports its own code.

Sources

  • Python Standard Library, subprocess — run and CompletedProcess, capture_output and text mode, the input argument, check and CalledProcessError, timeout and TimeoutExpired, and the list form for commands.
  • Python Standard Library, sys — sys.executable, sys.argv, and the stdin, stdout, and stderr streams a child inherits or captures.

Keep Exploring