Run a shell command from Python, capture output, and fail properly on error.

IntermediateHands-onPython for DevOps
Answer
import subprocess

result = subprocess.run(
    ["kubectl", "get", "nodes", "-o", "name"],
    capture_output=True, text=True, check=True, timeout=30,
)
nodes = result.stdout.split()
print(f"{len(nodes)} nodes")

On failure, check=True raises CalledProcessError with .returncode and .stderr.

Key trick → Pass a list and avoid shell=True. Then no shell parses your input, which removes command injection when arguments come from users.

All Real-World Interview questions Roadmap: Interview readiness

More on Python for DevOps