Sub topic 2
Your first command with subprocess.run
This chapter assumes you know basic Python syntax, functions and exceptions. It also assumes you can use a terminal and know that programs have standard input, standard output and standard error. It covers the core call, subprocess.run, and the object it returns. Later chapters cover arguments, output capture details, errors and timeouts.
What subprocess.run does
subprocess.run starts another program as a child process. It waits until the child finishes, then returns a CompletedProcess object. For most jobs, this one function is all you need.
The first argument is the command. Pass it as a list. The first item is the program, and the rest are its arguments.
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 examples use sys.executable, the path of the running Python interpreter, so they work on any system where Python runs.
Reading the CompletedProcess
The returned object holds the outcome of the run.
| Attribute | Meaning |
|---|---|
| `args` | The command you passed in |
| `returncode` | The child's exit status. `0` means success by convention |
| `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 stdout and stderr attributes are None unless you ask for capture. A common mistake is to call result.stdout.strip() without capturing, which raises AttributeError.
The three options in the example
capture_output=Truecollects the child's standard output and standard error instead of letting them print to your terminal.text=Truedecodes the captured output intostr. Without it you getbytes.check=Trueraisessubprocess.CalledProcessErrorif the exit status is not zero. Without it, a failed command passes silently and you must inspectreturncodeyourself.
What happens during a call
The call blocks. Your program does nothing else until the child exits.
Seeing a non-zero exit
Try a command that fails, without check=True:
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import sys; sys.exit(3)"],
)
print(result.returncode)The call returns normally and prints 3. No exception is raised, because you did not ask for one. Whether a non-zero code is an error depends on the program. Some tools use it to report a result, not a failure.
Common mistakes
- Passing a single string with spaces, such as
"ls -l", withoutshell=True. On POSIX systems this tries to run a program literally namedls -land fails. Use a list:["ls", "-l"]. - Forgetting
text=Trueand then treatingstdoutas a string. You will getbytes, and string methods withstrarguments will raiseTypeError. - Assuming
runreturns the output directly. It returns aCompletedProcess. The output lives in itsstdoutattribute.
Exercise
You run result = subprocess.run([sys.executable, "-c", "print('hi')"], text=True) and then print(result.stdout.upper()). What happens, and what single change fixes it?
Show answer
It raises AttributeError, because stdout is None when output is not captured. The child's output went straight to your terminal. Adding capture_output=True makes result.stdout the string "hi\n", so the call prints "HI".
Exercise
What is the difference between a command that exits with status 1 when you pass check=True and when you leave it out?
Show answer
With check=True, run raises CalledProcessError. Without it, run returns normally and the status is available as result.returncode.