Interview Prep/Python for DevOps/Automation scripting & CLI design

Someone asks you to "just add `shell=True`" because a pipe in `subprocess.run` does not work. What do you do?

IntermediateScenarioAutomation scripting & CLI design
Answer

Situation read → The command includes user-controlled input; shell=True would open command injection.

What I'd do →

  1. Do the pipe in Python: run the first command, process stdout in Python (often replacing grep/awk entirely).
  2. If both commands must stay, chain two Popen objects with stdout=PIPE and stdin=p1.stdout.
  3. If shell features are truly required with a constant command, use shell=True only with values passed through shlex.quote().
p1 = subprocess.Popen(["journalctl", "-u", unit, "--since", "1h ago"], stdout=subprocess.PIPE)
p2 = subprocess.run(["grep", "-c", "ERROR"], stdin=p1.stdout, capture_output=True, text=True)
p1.stdout.close(); p1.wait()

Why → Avoiding the shell eliminates the injection class instead of trying to sanitize it.

Interview tip → Say "list arguments, no shell" as the default rule.

All Python for DevOps questions Roadmap: Python for automation

More on Automation scripting & CLI design