Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Module

subprocess

The subprocess module launches external programs, connects to their standard streams, and reports their completion status. Use run() for typical commands and Popen for advanced process management.

How it works

The module starts external processes and provides ways to connect their standard input, output, and error streams while collecting a completion status. Use subprocess.run() for ordinary commands; use Popen when you need lower-level process control or interaction.

Syntax

subprocess.run(*args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

Parameters

NameTypeDescription
argssequence or path-like commandProgram and arguments to execute; commonly supplied as a sequence.
capture_outputboolCapture standard output and standard error together on the result.
shellboolRun the command through a shell; defaults to false.
checkboolRaise CalledProcessError when the command exits unsuccessfully.
timeoutfloat or int secondsMaximum time to wait before timing out.
textboolDecode streams as text rather than returning bytes.

Returns

subprocess.run() returns a CompletedProcess instance after the command finishes; its returncode attribute contains the child process's return status.

Key points

  • subprocess starts external programs and can connect the parent to their standard input, output, and error streams.
  • Use subprocess.run() for commands that can be expressed as one bounded operation.
  • Use Popen when you need ongoing process management, incremental I/O, or other control beyond run().
  • run() blocks until the child exits and returns a CompletedProcess containing its outcome.
  • The command and its arguments are supplied through the positional args accepted by run().

Common mistakes

  • A timeout raises TimeoutExpired; handle it when a command must be bounded, and remember that process cleanup may need explicit handling with lower-level APIs.

Example: Run a command safely

import subprocess

result = subprocess.run(
    ["python", "-c", "print('hello')"],
    capture_output=True,
    text=True,
    check=True,
)
print(result.stdout.strip())

Runs a child Python process without a shell, captures its standard output as text, and raises an exception if it fails.

When to use it

Invoke command-line tools

Run a formatter, compiler, version command, or other external utility and wait for completion.

Capture process streams

Collect a child program's standard output and error for parsing or logging.

Manage advanced child processes

Use Popen for interactive protocols, long-running children, or customized process supervision.

Interview questions

QWhat does subprocess.run() return?

subprocess.run() executes the supplied command, waits for completion, and returns a CompletedProcess object. Its arguments can configure input, output capture, environment, working directory, timeout, text decoding, and failure checking.

Follow-up: How would you make a failed command raise? Set check=True; a nonzero exit status then raises CalledProcessError instead of merely appearing in returncode.

QWhen should shell=True be avoided?

With shell=False, pass the executable and its arguments as a sequence, such as ["git", "status"]. With shell=True, a shell interprets the command string, which can introduce injection risk for untrusted input.

Follow-up: Why prefer a sequence even when shell features are unnecessary? It avoids shell parsing and separates the executable from its arguments, reducing ambiguity and security risk.

QHow do you capture command output as text?

capture_output=True redirects both standard output and standard error so they can be returned on the CompletedProcess object. Setting text=True requests text streams instead of bytes, using the selected or default encoding.

Follow-up: How can input be sent to the child? Use input= with subprocess.run(); it is incompatible with also supplying stdin explicitly.

  • subprocess.run
  • subprocess.Popen
  • subprocess.CompletedProcess
  • subprocess.PIPE
  • subprocess.DEVNULL
  • subprocess.STDOUT
  • subprocess.TimeoutExpired
  • subprocess.CalledProcessError

Source: subprocess — Subprocess management — Python 3.15.0. Checked 2026-10-16.