Sub topic 2
Checking Exit Codes and Controlling External Commands
Assume you know basic Python exceptions, can use a terminal, and understand standard input, standard output, standard error, text, and bytes. This chapter uses subprocess.run, which starts a program, waits for it, and returns a CompletedProcess.
Checking exit codes
A command reports success or failure through its exit code. By convention, 0 means success. A nonzero value usually means an error.
import subprocess
import sys
try:
subprocess.run(
[sys.executable, "-c", "import sys; sys.exit(3)"],
check=True,
)
except subprocess.CalledProcessError as exc:
print("command failed with code", exc.returncode)With check=True, Python raises CalledProcessError instead of returning normally when the command fails. Without it, inspect result.returncode yourself.
When the program cannot be started
A nonzero exit code means the program started and then reported failure. A launch failure happens earlier. For example, if the executable does not exist, Python raises FileNotFoundError.
import subprocess
try:
subprocess.run(["program-that-does-not-exist"], check=True)
except FileNotFoundError:
print("executable was not found")Handle launch errors separately from errors reported by the child process.
Stopping commands that run too long
Pass timeout to limit how long run waits. If the limit expires, Python stops the child and raises TimeoutExpired.
import subprocess
import sys
try:
subprocess.run(
[sys.executable, "-c", "import time; time.sleep(10)"],
timeout=1,
check=True,
)
except subprocess.TimeoutExpired as exc:
print("timed out after", exc.timeout, "seconds")Feeding input to a command
Use input to write data to standard input. Set text=True when sending and receiving strings.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import sys; print(sys.stdin.read().upper())"],
input="hello",
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())Setting environment and working directory
Use env to provide environment variables and cwd to choose the child’s starting directory. Preserve the existing environment when adding a variable.
import os
import subprocess
import sys
import tempfile
result = subprocess.run(
[sys.executable, "-c", "import os; print(os.environ['MODE']); print(os.getcwd())"],
env={**os.environ, "MODE": "test"},
cwd=tempfile.gettempdir(),
capture_output=True,
text=True,
check=True,
)
print(result.stdout)Exercise
Which exception indicates that a command started but returned a nonzero exit code when check=True?
Show answer
CalledProcessError.