subprocess and Safe OS Automation
Scenario: A script must invoke tar without letting a filename become a shell command.
New words, in plain English
- Subprocess - another program started by your Python process
- Shell injection - untrusted text being interpreted as shell syntax
- Standard output - a process's normal output stream
- Return code - the process success/failure number
Use subprocess.run with an argument list, check=True, and text=True. Capture output when needed. Avoid shell=True; use shutil and pathlib for file operations instead of spawning commands.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
import subprocess
result = subprocess.run(
["git", "status", "--short"],
check=True, capture_output=True, text=True, timeout=10,
)
print(result.stdout)
Tip: Set a timeout for external commands that could hang.
Goal: Practice this idea in the py-subprocess-automation challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.