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.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?Intermediate