Sub topic 6
When the program cannot be started
This chapter assumes you know subprocess.run, the check=True option and CalledProcessError, and Python's exception hierarchy.
Two different kinds of failure
A command can fail in two ways, and Python reports them differently.
- The program starts, runs and exits with a non-zero code. With
check=True,runraisesCalledProcessError. - The operating system cannot start the program at all. There is no child process and no exit code.
runraises anOSErrorsubclass.
CalledProcessError belongs to SubprocessError, not to OSError. An except OSError clause will not catch a failing exit code, and except subprocess.CalledProcessError will not catch a missing program.
Catching a missing program
The most common launch error is FileNotFoundError. It occurs when the name is misspelled or the program is not installed. It also occurs when the program is not on PATH, the list of directories the system searches for executables.
import subprocess
try:
subprocess.run(["no-such-program", "--version"], check=True)
except FileNotFoundError as exc:
print("could not start:", exc.filename)Handling each case separately
Put the launch errors and the exit-code error in separate except clauses. Each clause then reports a different cause.
import subprocess
import sys
def run_tool(cmd):
try:
return subprocess.run(cmd, capture_output=True, text=True, check=True)
except FileNotFoundError:
print("not found:", cmd[0])
except PermissionError:
print("not executable:", cmd[0])
except subprocess.CalledProcessError as exc:
print("started but failed with code", exc.returncode)
return None
run_tool(["no-such-program"])
run_tool([sys.executable, "-c", "import sys; sys.exit(2)"])The first call prints not found: no-such-program. The second prints started but failed with code 2.
PermissionError means the file exists but cannot be run. Typical causes are a missing execute bit on a script, or passing a directory instead of a program. If you do not need to tell the causes apart, catch OSError, the parent of both.
Checking before you run
shutil.which searches PATH the same way the system does. It returns the full path, or None if nothing matches.
import shutil
if shutil.which("git") is None:
print("git is not installed")Use this check to give users a clear message, such as an install hint. Do not treat it as a guarantee. The program can still disappear between the check and the launch, so keep the except clause.
Two traps
A bad cwd looks like a missing program. If the directory you pass as cwd does not exist, Python raises FileNotFoundError. The program name may be perfectly valid. Read the exception's message and filename before you assume the program is missing.
shell=True hides the error. The shell starts successfully, so Python has nothing to raise. The shell then reports the failure through its exit code.
import subprocess
result = subprocess.run("no-such-program", shell=True, stderr=subprocess.DEVNULL)
print(result.returncode)On Linux and macOS this prints 127, the shell's "command not found" code. On Windows the code is typically 1. Code that relies on FileNotFoundError stops working the moment you add shell=True.
Exercise
A function calls subprocess.run(["convert", "a.png", "b.jpg"], check=True) inside try/except subprocess.CalledProcessError. On a machine without ImageMagick installed, the program crashes with a traceback. Why, and what is the fix?
Show answer
With no convert program on the system, the launch fails before any child process exists, so Python raises FileNotFoundError. That is an OSError, not a CalledProcessError, so the except clause does not match. Add an except FileNotFoundError clause (or check shutil.which("convert") first) to report that the tool is missing.