Why is `shell=True` dangerous, and when is it acceptable?
IntermediateConceptOS, filesystem, subprocess & CLIs
Answer
With shell=True, the string is passed to /bin/sh -c, so any shell metacharacters in interpolated input execute. subprocess.run(f"git checkout {branch}", shell=True) with branch = "main; rm -rf ~" is command injection.
Acceptable only with fully constant strings where you genuinely need shell features (pipes, globbing) and no user input. Even then it is usually better to do the pipe in Python or quote with shlex.quote(). Bandit flags this as B602.
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?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerHow do you handle a failed command and show useful output?Intermediate