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

How do you run an external command correctly with `subprocess`?

BeginnerConceptOS, filesystem, subprocess & CLIs
Answer
import subprocess
result = subprocess.run(
    ["kubectl", "get", "pods", "-n", ns, "-o", "json"],
    check=True,            # raise CalledProcessError on non-zero exit
    capture_output=True,   # capture stdout and stderr
    text=True,             # str instead of bytes
    timeout=60,            # raise TimeoutExpired instead of hanging forever
)
pods = json.loads(result.stdout)

Pass a list of arguments, not a string, so there is no shell parsing and no injection. Always set a timeout for anything that talks to the network.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs