26. Running Commands with subprocess
The subprocess module lets Python run external commands. This is useful when you want to automate shell tools, capture output, or check whether a command succeeded.
26.1. Running a command
The simplest pattern is subprocess.run() with a list of arguments.
1import subprocess
2
3subprocess.run(['python3', '-c', "print('hello from subprocess')"])
26.2. Capturing output
If you need the command output inside Python, capture it explicitly.
1import subprocess
2
3result = subprocess.run(
4 ['python3', '-c', "print('captured output')"],
5 capture_output=True,
6 text=True,
7 check=True,
8)
9
10print(result.stdout.strip())
26.3. Checking failures
Use check=True if a non-zero exit status should raise an exception.
1import subprocess
2
3try:
4 subprocess.run(
5 ['python3', '-c', 'import sys; sys.exit(1)'],
6 check=True,
7 )
8except subprocess.CalledProcessError as exc:
9 print(f'command failed with status {exc.returncode}')
26.4. Exercise
Write a script that runs two external commands: one that succeeds and one that fails. Capture the output of the successful command and catch the exception from the failing one.
26.4.1. Solution
1import subprocess
2
3ok = subprocess.run(['python3', '-c', "print('hello')"], capture_output=True, text=True, check=True)
4print(ok.stdout.strip())
5
6try:
7 subprocess.run(['python3', '-c', 'import sys; sys.exit(1)'], check=True)
8except subprocess.CalledProcessError as exc:
9 print(f'command failed: {exc.returncode}')