Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

Handling Subprocess Errors/shaare/wBVnmg

  • python
  • python

Handling Subprocess Errors

  • External commands can fail in multiple ways: non-zero exit codes, missing executables, or hanging processes.
  • Using subprocess.run(..., check=True) shifts return-code checks into exceptions you can catch.
  • Specific exception types (CalledProcessError, FileNotFoundError, TimeoutExpired) let you distinguish failure modes and respond appropriately.

subprocess.CalledProcessError Attributes

  • e.returncode: the non-zero exit status of the command.
  • e.cmd: the exact command invoked (list or string form).
  • e.stdout / e.output: captured standard output, if capture_output=True.
  • e.stderr: captured standard error, if capture_output=True.
  • These attributes let you log or display detailed diagnostics when a command fails.
import subprocess

cmd = ["ls", "missing_dir"]

try:
    subprocess.run(cmd, check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as err:
    print(f"Command executed: {err.cmd}")
    print(f"Return code {err.returncode}")
    print(f"STDOUT capture: {err.stdout}")
    print(f"STDERR capture: {err.stderr}")

Handling FileNotFoundError

  • If the executable itself isn’t in PATH, subprocess.run() raises FileNotFoundError before running.
  • Catching it separately lets you inform the user that a required tool isn’t installed, rather than treating it as a generic failure.
import subprocess

cmd = ["fakecmd", "--version"]

try:
    subprocess.run(cmd, check=True, capture_output=True, text=True)
except FileNotFoundError as err:
    print("FileNotFoundError caught!")
    print(f"  The command '{cmd[0]}' was not found on this system.")

Handling subprocess.TimeoutExpired

  • Adding timeout=<seconds> to subprocess.run() kills the process if it runs too long.
  • A TimeoutExpired exception is raised, containing cmd, timeout, and any partial stdout/stderr.
  • Use this to prevent hung scripts and to implement retry or fallback logic.
import subprocess

cmd = ["sleep", "5"]

try:
    subprocess.run(cmd, timeout=2, capture_output=True, text=True)
    print("Command completed within timeout.")
except subprocess.TimeoutExpired as err:
    print("TimeoutExpired caught!")
    print(f"  Command: {err.cmd}")
    print(f"  Timeout after {err.timeout} seconds")

Recommended Error Handling Strategy

  • Wrap subprocess.run() in a try block.
  • First catch FileNotFoundError to detect missing executables.
  • Next catch subprocess.TimeoutExpired if you use timeouts.
  • Then catch subprocess.CalledProcessError for non-zero exits.
  • Finally, if necessary, an except Exception block can log any other unexpected issues.
  • This layered approach keeps your script robust and your errors informative.

+++

1 month ago Permalien
cluster icon
  • *args and **kwargs : Flexible Functions: *args and **kwargs We can use the syntax *args and **kwargs to accept a variable number of both positional and keyword arguments....
  • Python package and subpackage : Introduction to Packages (__init__.py) What is a Package? A Python package provides a way to structure a project's module namespace by using directori...
  • List : Lists (list) Lists are ordered, mutable sequences defined with square brackets []. You can add, remove, or change items after creation. Characteristic...
  • Making HTTP Requests : Making HTTP Requests The requests library simplifies HTTP interactions by abstracting raw HTTP details, making it ideal for DevOps automation tasks. ...
  • Generators : Generators Writing a class-based iterator requires __iter__() and __next__(), plus manual state management and StopIteration handling. Generator fu...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli