Sub topic 6
When the program cannot be started
This chapter assumes you have read the earlier chapters on subprocess.run, return codes and check=True. You should be comfortable with Python exceptions and their class hierarchy.
So far, failure meant that the program started and then exited with a non-zero code. A different kind of failure happens earlier: the operating system cannot start the program at all. Python reports this with an exception from the OSError family, not with a return code. Handling the two cases separately makes your error messages accurate.
Two kinds of failure
subprocess.run can fail in two different places:
- Launch failure. The operating system refuses to create the child process. No code from the program ever runs. Python raises
OSErroror one of its subclasses, such asFileNotFoundError. - Run failure. The program starts, runs and exits with a non-zero status.
runreturns normally, or raisesCalledProcessErrorif you passedcheck=True.
The two groups of exceptions are unrelated in the class hierarchy. CalledProcessError and TimeoutExpired inherit from subprocess.SubprocessError. Launch failures inherit from OSError. An except subprocess.SubprocessError clause will therefore not catch a missing program, and an except OSError clause will not catch a non-zero exit.
FileNotFoundError: the common case
The most frequent launch failure is a program name that does not exist, or one that is not on the PATH. The cause is often a typo, or a tool that is not installed on the machine.
import subprocess
try:
subprocess.run(["no-such-program-xyz"], check=True)
except FileNotFoundError as exc:
print("could not start:", exc.filename)
print("errno:", exc.errno)
print("reason:", exc.strerror)The exception carries three useful attributes:
filenameis the program name you passed, or the directory in the case described below.errnois the numeric operating system error. It is2(ENOENT) for a missing file on Linux, macOS and Windows.strerroris the operating system's message. Its wording differs between systems, so use it for display and never compare against it.
Do not parse str(exc) to decide what to do. Use the exception class and errno.
A missing working directory looks the same
If you pass a cwd that does not exist, you also get an error from the same family. On Linux and macOS it is a FileNotFoundError, and the filename attribute holds the directory, not the program.
import os
import subprocess
import sys
import tempfile
missing_dir = os.path.join(tempfile.gettempdir(), "does-not-exist-12345")
try:
subprocess.run([sys.executable, "-c", "pass"], cwd=missing_dir)
except OSError as exc:
print(type(exc).__name__)
print("problem path:", exc.filename)This is a real source of confusion. The message says "No such file or directory", and the program you named is fine. Check exc.filename before you tell a user to install something. On Windows the same mistake can raise NotADirectoryError instead, which is another reason to catch OSError when you want to cover every launch problem.
PermissionError and other OSError cases
A program can exist and still fail to start. On Linux and macOS, the file must have its execute bit set, and every directory in its path must be searchable by your user. If not, Python raises PermissionError (errno 13).
import os
import subprocess
import tempfile
with tempfile.TemporaryDirectory() as folder:
script = os.path.join(folder, "tool.sh")
with open(script, "w") as handle:
handle.write("#!/bin/sh\necho hi\n")
os.chmod(script, 0o644) # readable, but not executable
try:
subprocess.run([script], check=True)
except PermissionError as exc:
print("not executable:", exc.filename)This example is for Linux and macOS. Windows decides what is runnable by file extension, not by permission bits, so chmod has no equivalent effect there.
Other launch failures also surface as plain OSError with a specific errno:
| Situation | Exception | Typical errno (Linux) |
|---|---|---|
| Program not found on `PATH` | `FileNotFoundError` | 2 |
| Working directory does not exist | `FileNotFoundError` | 2 |
| File exists but is not executable | `PermissionError` | 13 |
| File is a script with no shebang line, or a binary for another architecture | `OSError` | 8 (`ENOEXEC`) |
| Too many processes or open files | `OSError` | 11 or 24 |
The last row matters in long-running services. Running out of file descriptors or process slots is a resource problem, and retrying immediately usually fails again.
Popen raises the same exceptions as run, because run is built on Popen. The error appears when you create the Popen object, before you can read any output.
shell=True hides launch failures
With shell=True, Python starts a shell, and the shell tries to start your program. The shell itself starts fine, so there is no launch failure from Python's point of view. The failure moves into the return code.
import subprocess
result = subprocess.run(
"no-such-program-xyz",
shell=True,
capture_output=True,
text=True,
)
print("return code:", result.returncode)
print("has error text:", bool(result.stderr))On Linux and macOS, /bin/sh reports "command not found" on standard error and exits with code 127. Code 126 means "found but cannot execute". On Windows, cmd.exe returns 1. No FileNotFoundError is raised in any of these cases.
If your code only catches FileNotFoundError, a shell=True call to a missing tool will slip past it. With check=True you would get a CalledProcessError with a vague code. Prefer an argument list, as covered earlier, and you get the clearer exception.
Failures inside the child are not launch failures
Do not mix up your program failing to start with the child program failing to find something. Suppose you run cat missing.txt. The cat program starts correctly, then reports that missing.txt does not exist, and exits with code 1. Python raises no FileNotFoundError. You see a return code and text on standard error. Likewise, a Python child that raises an exception exits with code 1, and its traceback goes to its standard error.
The rule is that a FileNotFoundError from run refers to the program or the cwd you gave. Everything the child does after it starts shows up in its output and exit status.
Checking before you run
You can test whether a program exists before running it with shutil.which. It searches the PATH the way a shell does and returns the full path, or None.
import shutil
for name in ["python3", "no-such-program-xyz"]:
location = shutil.which(name)
print(name, "->", location)On Windows, shutil.which also applies the PATHEXT extensions, so which("git") can find git.exe. This helps you give a clear message such as "please install git" early, before doing other work.
A check is not a guarantee. The file can be deleted, or its permissions changed, between the check and the run. Treat shutil.which as a courtesy for better messages, and still handle the exception around the actual call.
A helper that separates the outcomes
This helper keeps each kind of failure distinct. Order matters only where classes are related. FileNotFoundError and PermissionError are subclasses of OSError, so list them before a general OSError clause.
import subprocess
import sys
def run_tool(command):
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
check=True,
timeout=5,
)
except FileNotFoundError as exc:
return f"missing: {exc.filename}"
except PermissionError as exc:
return f"not executable: {exc.filename}"
except OSError as exc:
return f"cannot start (errno {exc.errno}): {exc.strerror}"
except subprocess.CalledProcessError as exc:
return f"failed with exit code {exc.returncode}"
except subprocess.TimeoutExpired:
return "timed out"
return "ok: " + result.stdout.strip()
print(run_tool([sys.executable, "-c", "print('fine')"]))
print(run_tool([sys.executable, "-c", "import sys; sys.exit(4)"]))
print(run_tool(["no-such-program-xyz"]))Running it prints one line for each outcome: ok: fine, failed with exit code 4 and missing: no-such-program-xyz.
What to do when you catch a launch error
The right reaction depends on who can fix the problem:
- For a missing program, report the name and, if you know it, how to install it. Do not retry.
- For
PermissionError, report the path and suggest checking the execute permission. - For resource errors such as
EMFILEorEAGAIN, a short wait and a limited number of retries can make sense. Also look for leaked file handles or runaway child processes in your own code. - For unexpected
OSErrorvalues, logerrno,strerrorandfilename, and re-raise if you cannot recover.
Exercise
A script calls subprocess.run("convert image.png out.jpg", shell=True, check=True) on Linux, and the convert tool is not installed. The author wrapped the call in except FileNotFoundError, but the handler never runs. Which exception does the script raise instead, and how would you change the call so the handler works?
Show answer
The shell starts successfully and reports "command not found" with exit code 127, so check=True raises subprocess.CalledProcessError with returncode 127. To get FileNotFoundError, pass an argument list and drop the shell: subprocess.run(["convert", "image.png", "out.jpg"], check=True). Python then tries to start convert itself and raises FileNotFoundError with filename set to "convert".
Exercise
You call subprocess.run(["ls"], cwd="/data/reports") and get FileNotFoundError: [Errno 2] No such file or directory: '/data/reports'. A teammate says ls is not installed. How do you show that they are wrong?
Show answer
Read exc.filename. It is '/data/reports', the directory passed as cwd, not 'ls'. The program was found, and the error came from the missing working directory. You can confirm with shutil.which("ls"), which returns a path.