December 5, 2026

Python subprocess.run Examples: Capturing Output, Timeouts, and the Shell Flag That Lets a Filename Run Commands

A laptop terminal with a glowing branching diagram beside it

A Python script passed a filename to wc -c through subprocess.run(..., shell=True). The filename was report.txt; touch box/PWNED, and afterward a file called PWNED sat in the box folder. Python didn’t do anything wrong. The shell read the semicolon as the end of one command and the start of another, exactly as shells are meant to. The same call written with a list of arguments instead of a string would have treated the whole thing as one strange filename. That difference, and a handful like it, decides whether subprocess code is reliable or quietly dangerous. Every example below was run with Python 3.13 on Linux.

Video: Corey Schafer on YouTube

The basic call

run() is the starting point

Python’s subprocess documentation is direct about where to begin: “The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle.” The lower-level Popen class is for the cases it can’t.

Arguments as a list

import subprocess
subprocess.run(["echo", "hello"])

That printed hello, then returned CompletedProcess(args=['echo', 'hello'], returncode=0). The first list item is the program; each later item is passed to it as one argument, with no shell involved.

A string without shell=True fails

Passing "echo hi there" as a single string, without shell=True, raised FileNotFoundError: [Errno 2] No such file or directory: 'echo hi there'. Python looked for a program literally named echo hi there. On Linux, a string command needs either a list or the shell.

Focus photo of brown sand

Capturing output, exit codes and input

capture_output and text

r = subprocess.run(["ls", "-l", "/nonexistent"], capture_output=True, text=True)

The result had returncode 2, an empty stdout, and stderr holding ls: cannot access '/nonexistent': No such file or directory. capture_output=True collects both streams instead of printing them, and text=True returns strings rather than bytes.

Failures don’t raise by default

That ls call failed, and Python said nothing. run() reports the exit code and leaves it to the caller to look. Adding check=True changes that; the documentation says a non-zero exit then raises CalledProcessError:

CalledProcessError: Command '['ls', '/nonexistent']' returned non-zero exit status 2.

Missing programs: two different symptoms

With a list, a program that doesn’t exist raised FileNotFoundError immediately. With shell=True, the shell started fine and then reported the problem itself: return code 127 and /bin/sh: 1: no-such-cmd: not found in stderr. Code that only catches the exception misses the shell version, and code that only checks return codes misses the list version.

Feeding stdin

r = subprocess.run(["wc", "-w"], input="one two three\n",
                   capture_output=True, text=True)

r.stdout came back as '3\n'. The input argument writes to the child’s standard input and closes it, so no temporary file is needed.

Adding to the environment, not replacing it

env= replaces the child’s entire environment, so the safe pattern copies the current one and adds to it:

import os
subprocess.run(["sh", "-c", "echo $MYVAR"],
               env={**os.environ, "MYVAR": "42"})

That printed 42. The **os.environ expression copies every existing variable into a new dictionary, and the extra key is added or overrides on top, so the parent process’s own environment stays untouched. Passing only {"MYVAR": "42"} would also strip HOME, LANG and everything else the child might rely on.

Working directory

cwd="box" runs the child inside that folder. pwd reported /tmp/sp/box, while the Python script itself never changed directory.

shell=True and injection

What happened with the filename

name = "report.txt; touch box/PWNED"
subprocess.run(f"wc -c {name}", shell=True)

The shell ran wc -c report.txt, then touch box/PWNED. Afterward, os.path.exists('box/PWNED') returned True. Swap touch for a delete command and the same flaw destroys data; swap it for a download and it installs something.

The documentation’s warning

The subprocess documentation’s security section says that with shell=True, “it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities,” and points to shlex.quote() for escaping on some platforms.

What shlex.quote() changes

Rerunning the attack with the name wrapped as shlex.quote(name) turned it into 'report.txt; touch box/PWNED2', single quotes included. The shell then passed the whole string to wc as one filename, wc complained that no such file existed, and no PWNED2 file appeared. The quoting worked, but only because the call remembered to use it; every variable in every shell string needs the same treatment.

Spaces break it too, without any attacker

A perfectly innocent file named a b.txt shows the same problem. The list form, ["wc", "-c", "box/a b.txt"], printed 1 box/a b.txt. The shell form, "wc -c box/a b.txt", failed with wc: box/a: No such file or directory, because the shell split the name at the space. Lists avoid both problems, because no shell ever reads the text.

A coiled green garden hose resting on gravel beside a dark wooden

Timeouts and the process left behind

timeout=

subprocess.run(["sleep", "5"], timeout=1)

That raised TimeoutExpired after 1.0 seconds. The documentation describes what happens: “If the timeout expires, the child process will be killed and waited for.”

The shell exception

“The child process” means the direct child. With shell=True, that child is the shell, not the command it starts. Running "sleep 30; echo done" with shell=True and a 1-second timeout raised TimeoutExpired as expected, and the shell was killed. A moment later, pgrep still found sleep 30 running. The command outlived its own timeout, orphaned rather than stopped.

Avoiding orphans

Running the program directly as a list makes it the child, so the timeout kills it. When a shell is unavoidable, the child can be started in its own session and the whole group killed on timeout:

import os, signal
p = subprocess.Popen("sleep 31; echo done", shell=True, start_new_session=True)
try:
    p.wait(timeout=1)
except subprocess.TimeoutExpired:
    os.killpg(p.pid, signal.SIGTERM)
    p.wait()

After that, pgrep found no sleep 31 left running.

What a kill looks like

After Popen(["sleep", "10"]).kill(), wait() returned -9. The documentation explains: “A negative value -N indicates that the child was terminated by signal N (POSIX only).” Signal 9 is SIGKILL.

Popen for streaming and the pipe deadlock

Reading output as it arrives

run() waits for the process to finish before returning anything. For a long job, Popen gives lines as they appear:

p = subprocess.Popen(["sh", "-c", "for i in 1 2 3; do echo line $i; sleep 0.2; done"],
                     stdout=subprocess.PIPE, text=True)
for line in p.stdout:
    print(line.strip())
p.wait()

The three lines arrived at 0.0, 0.2 and 0.4 seconds, as the child printed them.

The deadlock

A child writing 200,000 bytes into a pipe while the parent calls p.wait() froze. After 3 seconds, wait() was still blocked and had to be abandoned. The documentation warns that wait() “will deadlock when using stdout=PIPE or stderr=PIPE” when the child fills the operating system’s pipe buffer: the child waits for someone to read, and the parent waits for the child to exit.

communicate() avoids it

The same child with out, _ = p.communicate(timeout=3) returned all 200,000 bytes at once. communicate() reads the pipes while waiting, which is also what run() does internally with capture_output=True.

An hourglass with blue sand on a sandy beach

Text, bytes and merged streams

When text=True meets bad bytes

text=True decodes output using the locale’s encoding, UTF-8 on most Linux systems. A program that prints a Latin-1 é, the single byte 0xe9, breaks that:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte

Without text=True, the same call returned the raw bytes b'caf\xe9\n' with no error. Passing encoding="utf-8", errors="replace" swapped the bad byte for the replacement character, giving 'caf�\n', and encoding="latin-1" decoded it correctly as 'café\n'. Output from older tools, Windows programs and binary-ish logs is where this shows up.

Merging stderr into stdout

Some tools write progress to stderr and results to stdout, and the order between them matters when reading a log. stdout=subprocess.PIPE, stderr=subprocess.STDOUT sends both into one stream. A command printing out, then err to stderr, then out2 came back as 'out\nerr\nout2\n', in the order written.

Checking after the fact

When a script wants to inspect the output before deciding whether a failure matters, check=True is too early. CompletedProcess.check_returncode() raises the same CalledProcessError later, on demand. For a command that exited with 3, it raised Command '['sh', '-c', 'exit 3']' returned non-zero exit status 3.

Older helpers

subprocess.check_output() and check_call() predate run() and still work: check_output(["echo", "legacy"], text=True) returned 'legacy\n'. Existing code using them doesn’t need rewriting, but run() covers the same ground with one consistent set of options.

A short checklist

Defaults worth adopting

  • Pass a list of arguments; reach for shell=True only when the shell itself is truly needed.
  • Use check=True, or check returncode every time.
  • Use capture_output=True, text=True when the output matters.
  • Set timeout= on anything that could hang.
  • Extend os.environ rather than replacing it.
  • With Popen and pipes, read the output or use communicate(), never a bare wait().

When a shell is genuinely needed

Pipelines, redirection and globbing are things only the shell provides. They can usually be rebuilt in Python, by chaining Popen objects, opening files directly or using glob. When they can’t, every value that comes from outside the script gets wrapped in shlex.quote() before it goes into the command string.

Sources

  • subprocess — Subprocess management, Python 3 documentation: https://docs.python.org/3/library/subprocess.html

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *