Sub topic 2
Your first command with subprocess.run
This chapter covers subprocess.run: what it does, the object it returns, and the mistakes people most often make on a first attempt. It assumes you know basic Python syntax, functions and exceptions. It also assumes you can use a terminal, know that programs have standard input, standard output and standard error, and know that Python separates text (str) from bytes. Later chapters cover argument handling, timeouts, input and environment in depth. Here the goal is a correct working model of the basic call.
What run does
subprocess.run starts another program, waits until it exits, and returns a CompletedProcess object that describes the result. It is the function to reach for first. It is a convenience wrapper around the lower-level Popen class, which later chapters cover.
The sequence has four steps:
- Python asks the operating system to create a child process running the command.
- The parent (your Python program) blocks and does nothing else.
- The child runs to completion and exits with an integer exit status.
runreturns aCompletedProcessholding that status and any output you asked it to collect.
A first example
The examples use sys.executable, the path of the running Python interpreter, as the command. That makes them behave the same on any machine, because every system with Python has it. Substitute any program you like in your own code.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print('hello')"],
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())
print(result.returncode)This prints hello and then 0. The call has four parts:
- The first argument is a list. The first item is the program, and the remaining items are its arguments. Here the child is
python -c "print('hello')". No shell is involved, and each list item reaches the program as exactly one argument. capture_output=Trueconnects the child's standard output and standard error to pipes. Python reads them and stores the contents in the result.text=Truedecodes those captured bytes intostr. Without it,result.stdoutisbytes.check=Trueraises an exception if the child exits with a non-zero status. Without it, a failed command goes unnoticed unless you inspect the status yourself.
Only the first argument, args, can be passed by position in practice. Treat everything else as a keyword argument, as the example does.
What CompletedProcess contains
CompletedProcess is a small record with four attributes. This example makes a child that writes to both streams and fails on purpose, so you can see each one.
import subprocess
import sys
code = "import sys; print('out'); print('err', file=sys.stderr); sys.exit(2)"
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True,
)
print(result.args[1:2])
print(result.returncode)
print(repr(result.stdout))
print(repr(result.stderr))The output is:
['-c']
2
'out\n'
'err\n'The attributes mean the following:
| Attribute | Meaning |
|---|---|
| `args` | The command exactly as you passed it to `run` |
| `returncode` | The child's exit status. `0` conventionally means success |
| `stdout` | Captured standard output, or `None` if you did not capture it |
| `stderr` | Captured standard error, or `None` if you did not capture it |
The captured text keeps its trailing newline, which is why the example prints 'out\n'. Call .strip() or .rstrip("\n") when you want the bare value.
Because this call did not use check=True, the exit status of 2 did not raise anything. You can still ask for the exception afterwards with result.check_returncode(). It does nothing when the status is 0 and raises CalledProcessError otherwise. That is useful when you want to look at the output before deciding whether a failure matters. The next chapters on exit codes cover this in detail.
Output you do not capture
If you do not ask for capture, the child inherits your program's standard streams. Its output appears directly in your terminal, interleaved with your own prints. Python never sees it.
import subprocess
import sys
result = subprocess.run([sys.executable, "-c", "print('visible')"])
print(result.stdout)
print(result.returncode)The terminal shows visible, then None (the value of result.stdout), then 0. This is the right choice when you only want a command to run and show its progress, such as a build tool. It is the wrong choice when your code needs to read the output.
A related detail: the child's output and your own print output can appear out of order. The child writes through its own buffers, and so does your program. If ordering matters, flush with print(..., flush=True) before calling run.
Common mistakes
These are the errors that show up most often in first attempts.
Passing a single string. On Linux and macOS, subprocess.run("ls -l") without a shell looks for a program literally named ls -l. It raises FileNotFoundError. Pass ["ls", "-l"] instead. The chapter on arguments covers when a string is acceptable.
Forgetting text=True. The output is then bytes, and result.stdout.strip() == "hello" quietly evaluates to False because b"hello" is not equal to "hello". If you see a b'...' prefix in your output, this is the cause.
Expecting stdout to exist without capture. Without capture_output=True (or an explicit stdout=subprocess.PIPE), the attribute is None. Calling .strip() on it raises AttributeError.
Ignoring failure. A non-zero returncode is not an error as far as Python is concerned. A script that never checks it carries on as if the command had worked. Use check=True unless you have a reason to handle the status yourself.
Assuming shell features work. Wildcards such as *.txt, pipes with |, redirection with >, and built-ins such as cd are features of a shell, not of the program. With a list of arguments there is no shell, so ["ls", "*.txt"] looks for a file literally named *.txt. Do the equivalent work in Python, for example with pathlib.Path.glob, or use a shell deliberately after reading the chapter on injection.
Edge cases worth knowing
- On Linux and macOS, if the child is killed by a signal,
returncodeis negative. A value of-9means the child was killed by signal 9. On Windows, return codes are never negative in this way, so write code that only treats 0 as success. runblocks without limit by default. A child that waits for input or never finishes will hang your program forever. The timeout chapter shows the fix.capture_output=Trueis shorthand forstdout=subprocess.PIPE, stderr=subprocess.PIPE. Becauserunreads both pipes to the end before returning, it does not deadlock on large output, but all of that output is held in memory. For very large or endless output, usePopenand read as the data arrives.- The text decoding uses your locale's preferred encoding unless you pass
encoding="utf-8". Set it explicitly when the child's output encoding is known, so results do not depend on the machine.
Putting it together
A typical use is asking a tool for information and acting on it. This example asks the child Python interpreter for its version string and parses the result.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "--version"],
capture_output=True,
text=True,
check=True,
)
name, version = result.stdout.split()
print(name, version)This prints Python followed by the version number, for example Python 3.12.4. Old Python 2 releases wrote this text to standard error, and some other programs also print version information to stderr. If stdout is empty when you expect text, check result.stderr before assuming the command failed.
Exercise
A script runs result = subprocess.run(["git", "status", "--short"], text=True) and then calls result.stdout.splitlines(). It raises AttributeError, even though git works and prints the status to the terminal. What is wrong, and what is the smallest change that fixes it? Also name one further option you would add so a failing git command is not silently ignored.
Show answer
The call did not capture output, so the child wrote straight to the terminal and result.stdout is None, which has no splitlines method. Add capture_output=True to the call. To stop failures passing unnoticed, also add check=True, which raises CalledProcessError when git exits with a non-zero status.