Skip to content

Lesson 2 of 9 · 24m

subprocess Done Right

How to run external commands safely: argv arrays, timeouts, capture discipline, exit handling, shell avoidance, and cleanup of child processes.

Most Python automation eventually becomes a controller for tools written in other languages: ssh, rsync, tar, openssl, aws, git. The dangerous part is not launching a process; it is launching one with unclear input, no timeout, and no plan for the ten thousand lines it prints before hanging.

Pass argv as a list

import subprocess

result = subprocess.run(
    ['pg_dump', '--format=custom', '--file', str(outfile), database],
    check=True, text=True, capture_output=True, timeout=300,
)

The list form passes each argument exactly once to the operating system. Spaces in filenames stay spaces, and shell metacharacters stay inert data. This is the bug farm:

subprocess.run(f'pg_dump {database} --file {outfile}', shell=True)

Now a database named prod; rm -rf /something is command injection. If shell=True seems necessary, you are usually using the shell as a poor programming language inside Python.

Timeout is not optional

A process without a timeout is a script that will eventually hang forever:

try:
    subprocess.run(cmd, capture_output=True, text=True, timeout=120, check=True)
except subprocess.TimeoutExpired as exc:
    raise RuntimeError(f'command timed out after 120s: {cmd}') from exc

subprocess.run kills the direct child on timeout. If that child spawned a shell script with its own children, grandchildren can survive. For process trees, use start_new_session=True and kill the process group deliberately.

Capture output, but bound memory

capture_output=True buffers stdout and stderr. Fine for git rev-parse; not fine for a restore command logging one line per row. Stream noisy commands:

with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as proc:
    for line in proc.stdout:
        log.info('remote: %s', line.rstrip())
    rc = proc.wait(timeout=600)

Nonzero can be data or failure

check=True is correct when failure should stop the run. It is wrong when nonzero is meaningful: grep returns 1 for no match and higher values for real errors. Inspect returncode deliberately. Likewise pass env and cwd explicitly so cron, systemd, CI, and interactive shells execute the same program instead of four different interpretations of it.

Field notes

  • Use shlex.join(cmd) when logging command lines so spaces and shell-sensitive characters remain unambiguous.
  • stderr=subprocess.STDOUT slightly destroys ordering fidelity but often produces more useful operational logs.
  • Close stdin (stdin=subprocess.DEVNULL) for tools that might otherwise wait silently for input.
  • TimeoutExpired.stdout can be incomplete; do not parse it as a complete result.

Was this lesson helpful?

Sign in to rate