Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you handle a failed command and show useful output?

IntermediateConceptOS, filesystem, subprocess & CLIs
Answer
try:
    subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=120)
except subprocess.CalledProcessError as e:
    log.error("%s exited %d\nstdout:\n%s\nstderr:\n%s",
              shlex.join(e.cmd), e.returncode, e.stdout, e.stderr)
    raise
except subprocess.TimeoutExpired as e:
    log.error("%s timed out after %ss", shlex.join(e.cmd), e.timeout)
    raise
except FileNotFoundError:
    sys.exit(f"{cmd[0]} not found on PATH")

FileNotFoundError means the executable itself was not found, which is different from the command failing.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs