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.
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?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?IntermediateHow do you handle a failed command and show useful output?Intermediate