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 →
- Do the pipe in Python: run the first command, process
stdoutin Python (often replacinggrep/awkentirely). - If both commands must stay, chain two
Popenobjects withstdout=PIPEandstdin=p1.stdout. - If shell features are truly required with a constant command, use
shell=Trueonly with values passed throughshlex.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.
More on Automation scripting & CLI design
Your team has a 300-line Bash script that parses JSON with `jq`, loops over AWS accounts and retries with `sleep`. It breaks every month. Do you rewrite it in Python?BeginnerA colleague's script deletes files older than 30 days from `/var/log/app`. You are asked to review it before it goes into cron. What do you look for?IntermediateYou need a script that ops engineers run from laptops and that CI runs nightly. How do you design its interface?IntermediateA script reads a 15 GB access log to count 5xx errors per endpoint, and the box runs out of memory. How do you fix it?BeginnerYou must run the same Python automation on 40 servers that have Python 3.6, 3.9 and 3.12. What do you do?IntermediateA cron job that runs a Python script fails silently. Nobody noticed for two weeks. How do you make sure that never happens again?Intermediate