Definition
subprocess is the module of the Python §12.23 standard library that starts other programs as child processes, connects to their standard input, output and error streams, waits for them to end and returns their exit status §13.24. A process is a running program; the child is the process the program starts. The child’s command is given either as an argument list, whose elements the operating system hands to the child one by one, or as a command string with shell=True, which a command interpreter, the shell, parses as a small program.
The idea
A program counts the bytes of a file whose name a user typed. If the name is my notes.txt, an argument list delivers one argument, my notes.txt. The command string wc -c my notes.txt, given to a shell, delivers two arguments, my and notes.txt, because the shell splits words at spaces. If the name is a.txt; echo hacked, the shell sees two commands separated by the semicolon and runs both.
The core idea: an argument list is data, a command string is code. With a list, the boundaries between arguments are fixed by the list itself before any program runs, and no character inside an element means anything special. With a string, the shell decides the boundaries, and characters such as space, ;, |, &, >, $, quotes and backquotes have special meanings. Placing untrusted text inside a command string is like reading a stranger’s note aloud to a clerk who obeys every sentence instead of filing the note. The resulting attack is called command injection or shell injection. The picture stops at one point: quoting can make the clerk file the note after all, but only quoting that follows the exact rules of that clerk’s language.
How it works
The calls. subprocess.run(args, ...) starts the child, waits for it and returns a CompletedProcess object whose returncode holds the exit status and whose stdout and stderr hold any captured output. The common keyword arguments are these.
capture_output=Truecollects standard output and standard error;text=Truedecodes them to strings.inputsupplies bytes or text for the child’s standard input.check=TrueraisesCalledProcessErrorif the exit status is not 0.timeoutis a number of seconds; when it expires, the child is killed and waited for, andTimeoutExpiredis raised.cwdsets the child’s working directory.envreplaces the child’s whole environment, the named text settings such asPATHthat a process passes to its children; withoutenv, the child inherits the parent’s environment.
The class Popen offers the same steps one at a time, for a child that runs alongside the parent.
Argument list, shell=False (the default). On POSIX (Portable Operating System Interface) systems, such as Linux, Python creates the child and executes the program named by the first element. If that element contains no slash, the program is searched for in the directories listed in the environment setting PATH. The child’s argument vector, the array §14.5 of strings that a C program receives as argv, is exactly the list: element 0 names the program and each later element is one argument, spaces and punctuation included. No shell runs. An element may not contain a zero byte, because the operating system passes each argument as a string ended by a zero byte; Python raises ValueError instead.
Command string, shell=True. On POSIX systems Python runs the shell /bin/sh with the argument vector /bin/sh, -c, and the string. The shell splits the string into words at spaces and tabs, removes quotes, replaces $NAME by the value of a variable and * by matching file names, runs commands written inside $(...) or backquotes and inserts their output, and treats ;, &&, ||, |, > and < as command separators, pipes and redirections. Only then does it start the programs it found. Two mismatches are common. A plain string without shell=True is taken on POSIX as the name of one program, so run("ls -l") looks for a program called ls -l. A list with shell=True makes only its first element the command and passes the others to the shell itself, so run(["echo", "hi"], shell=True) prints an empty line.
Quoting, when a shell is truly needed. shlex.quote(s) returns a version of s that a POSIX shell reads as exactly one word with no special characters: it wraps the text in single quotes and writes each single quote inside it as '"'"', so it's becomes 'it'"'"'s'. shlex.split does the reverse for a trusted command line: it splits the line the way a POSIX shell would and returns a list. Neither function applies to cmd.exe, the Windows command interpreter, whose rules differ.
Windows. A Windows process receives its arguments as one command-line string, not as an array. Python joins a list into that string by the quoting rules of the Microsoft C runtime library, and the child splits the string again by whatever rules it uses itself. A batch file (.bat or .cmd) is always run by cmd.exe, so its arguments are parsed by the command interpreter even when they come from a list.
Streams. A pipe is a kernel buffer that carries bytes from one process to another, here from the child’s output to the parent. A pipe holds a limited number of bytes, and a child that fills it stops until the parent reads. run and Popen.communicate read all captured streams while they wait. Popen.wait() does not read, so calling it on a child whose output goes to an unread pipe can wait forever.
Worked example
A user supplies the file name a.txt; echo hacked, which is characters: a.txt;, a space, echo, a space, hacked.
List:
run(["wc", "-c", name]). The child’s argument vector has 3 elements:wc,-cand the 18-character name. One program runs.wcfinds no file with that odd name, reports the error and exits with status 1.String:
run("wc -c " + name, shell=True). The shell receiveswc -c a.txt; echo hackedand finds two commands:wcwith the 2 arguments-canda.txt, thenechowith the 1 argumenthacked. The second command was chosen by the user. A shell’s exit status is that of its last command, soreturncodeis 0 even ifwcfailed.Quoted string:
run("wc -c " + shlex.quote(name), shell=True). The shell receiveswc -c 'a.txt; echo hacked', removes the quotes and runs one command whose arguments are-cand the 18-character name, as in case 1.
A second example shows the pipe limit. A child writes 100,000 bytes to its standard output, which is a pipe, and the parent calls Popen.wait() before reading. On Linux a pipe holds 65,536 bytes by default. The child writes 65,536 bytes, and its next write waits for space, with bytes still unwritten. The parent waits for the child to end, and the child waits for the parent to read: a deadlock §9.14, in which each party waits for the other. run(..., capture_output=True) reads while it waits and finishes normally.
A third example shows the reach of timeout. run(["make"], timeout=5) starts the build tool make, which starts compilers as its own children. After 5 s, run kills make and raises TimeoutExpired, but the compilers already started keep running.
Stated precisely
On POSIX systems, run(L) with a list and shell=False starts a child whose argument vector is exactly , each element encoded to bytes. The program file is , looked up through PATH when contains no slash, unless the argument executable names a different file. Neither Python nor any shell interprets a character of any . With shell=True and a string , the argument vector is /bin/sh, -c, , and means whatever the POSIX shell grammar makes of it.
returncode is the exit status of the direct child: 0 by convention means success, a positive value is a status the program chose, and on POSIX systems a value means that signal number ended the child; , for example, means SIGKILL. The value describes that one process only, not the processes it started and not any effect it caused elsewhere.
When timeout expires, run kills the direct child (SIGKILL on POSIX systems, the function TerminateProcess on Windows), waits for it to end and raises TimeoutExpired. Descendants are not killed. On POSIX systems, a child started as p = Popen(args, start_new_session=True) leads a new process group, and os.killpg(p.pid, signal.SIGKILL) then kills every member of that group; a descendant that moves to another group escapes. Establishing that every descendant has ended is the subject of the process closure §13.23 entry.
Limits and common mistakes
A list stops the shell, not the child’s own parsing. An argument that begins with - can be read as an option: a file named --help makes many programs print help instead of reading the file. Programs that follow the usual convention treat -- as the end of options, as in ["rm", "--", name].
Some programs hand their arguments to a shell themselves. ssh joins its command arguments with spaces and the remote computer’s shell parses the result, so a list on the local side gives no protection on the remote side.
shell=True is rarely needed. A pipeline can be built by connecting two Popen objects with stdout=subprocess.PIPE, and wildcards can be expanded with the glob module.
Which program runs depends on PATH and, for a name containing a slash but not starting with one, on the current directory. A program that must run a particular file gives its absolute path.
An exit status of 0 is the child’s own report of success. It does not prove that the work the child requested elsewhere, such as a write on a remote server, has finished or will survive a crash.
timeout ends only the waiting and the direct child. Work that the child handed to other processes or other computers can continue.
Questions answered
How do argument lists differ from shell command strings?
An argument list fixes the new program’s arguments before anything runs, while a shell command string is a small program that a shell parses to decide which programs to run and with which arguments. With a list and shell=False, the default in Python’s subprocess module, each element becomes exactly one argument of the new program, and no character inside an element has a special meaning: a space, a semicolon or a dollar sign is just a character. With a string and shell=True, the string goes to a shell (/bin/sh -c on Linux and other POSIX systems, cmd.exe on Windows), which splits it into words and interprets quotes, variables, wildcards, command separators such as ;, pipes and redirections. Untrusted text inside such a string can therefore add commands, an attack called command injection.
The list removes the shell, but three checks remain: the child may read an argument that starts with - as an option, some programs (ssh, or a Windows batch file, which cmd.exe runs) pass their arguments to a shell anyway, and on Windows each program splits its single command-line string by its own rules. When a shell is unavoidable on a POSIX system, quote every untrusted value with shlex.quote.
Related entries: argparse (§12.37), Deterministic replay (§10.37), Exactly-once effect (§8.32), Asynchronous completion (§9.28), Process closure (§13.23), Exit status (§13.24), Deadlock (§9.14). Further reading: [35, 50].