Back
+15 XP
Concept

Capturing Standard Error & Return Codes

Every CLI process returns an exit code (`0` = success, non-zero = failure). Use `check=True` in `subprocess.run` to raise `CalledProcessError` on failure 🛑.

python
import subprocess

try:
    # check=True raises CalledProcessError if returncode != 0
    res = subprocess.run(["false"], check=True, capture_output=True)
except subprocess.CalledProcessError as err:
    print(f"Command failed with exit code: {err.returncode} 🛑")

# 103. Capturing Standard Error & Return Codes Every CLI process returns an exit code (`0` = success, non-zero = failure). Use `check=True` in `subprocess.run` to raise `CalledProcessError` on failure 🛑. ```python import subprocess try: # check=True raises CalledProcessError if returncode != 0 res = subprocess.run(["false"], check=True, capture_output=True) except subprocess.CalledProcessError as err: print(f"Command failed with exit code: {err.returncode} 🛑") ``` Always inspect `err.stderr` when catching `CalledProcessError` to print the exact diagnostic error message emitted by the failed CLI utility! 🛑 --- ### Question What does an exit code of `0` conventionally signify in Unix and Windows systems? 🧠 - [ ] a. Successful execution without errors ✅ - [ ] b. Fatal segmentation fault - [ ] c. Command timed out - [ ] d. Standard output buffer overflow --- ### Challenge Run `subprocess.run(['true'], capture_output=True)`. Print whether `result.returncode == 0`. 🎯 <details> <summary>Solution</summary> ```python import subprocess result = subprocess.run(["true"], capture_output=True) print(result.returncode == 0) ``` </details>

Checkpoint

What does an exit code of `0` conventionally signify in Unix and Windows systems? 🧠

Practice

Run `subprocess.run(['true'], capture_output=True)`. Print whether `result.returncode == 0`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks