1. Nick Coghlan
  2. cpython_sandbox


cpython_sandbox / Doc / library / subprocess.rst

:mod:`subprocess` --- Subprocess management

The :mod:`subprocess` module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as:


Information about how the :mod:`subprocess` module can be used to replace these modules and functions can be found in the following sections.

Using the :mod:`subprocess` Module

The recommended approach to invoking subprocesses is to use the following convenience functions for all use cases they can handle. For more advanced use cases, the underlying :class:`Popen` interface can be used directly.

Frequently Used Arguments

To support a wide variety of use cases, the :class:`Popen` constructor (and the convenience functions) accept a large number of optional arguments. For most typical use cases, many of these arguments can be safely left at their default values. The arguments that are most commonly needed are:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be :const:`True` (see below) or else the string must simply name the program to be executed without specifying any arguments.

stdin, stdout and stderr specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive integer), an existing file object, and None. :data:`PIPE` indicates that a new pipe to the child should be created. :data:`DEVNULL` indicates that the special file :data:`os.devnull` will be used. With the default settings of None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be :data:`STDOUT`, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.

If universal_newlines is True, the file objects stdin, stdout and stderr will be opened as text streams in :term:`universal newlines` mode using the encoding returned by :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>`. For stdin, line ending characters '\n' in the input will be converted to the default line separator :data:`os.linesep`. For stdout and stderr, all line endings in the output will be converted to '\n'. For more information see the documentation of the :class:`io.TextIOWrapper` class when the newline argument to its constructor is None.


The newlines attribute of the file objects :attr:`Popen.stdin`, :attr:`Popen.stdout` and :attr:`Popen.stderr` are not updated by the :meth:`Popen.communicate` method.

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user's home directory. However, note that Python itself offers implementations of many shell-like features (in particular, :mod:`glob`, :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`, :func:`os.path.expanduser`, and :mod:`shutil`).


Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input:

>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / #
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...

shell=False disables all shell based features, but does not suffer from this vulnerability; see the Note in the :class:`Popen` constructor documentation for helpful hints in getting shell=False to work.

When using shell=True, :func:`shlex.quote` can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands.

These options, along with all of the other options, are described in more detail in the :class:`Popen` constructor documentation.

Popen Constructor

The underlying process creation and management in this module is handled by the :class:`Popen` class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.


Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called :attr:`child_traceback`, which is a string containing traceback information from the child's point of view.

The most common exception raised is :exc:`OSError`. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for :exc:`OSError` exceptions.

A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid arguments.

:func:`check_call` and :func:`check_output` will raise :exc:`CalledProcessError` if the called process returns a non-zero return code.

All of the functions and methods that accept a timeout parameter, such as :func:`call` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if the timeout expires before the process exits.

Exceptions defined in this module all inherit from :exc:`SubprocessError`.


Unlike some other popen functions, this implementation will never call a system shell implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Obviously, if the shell is invoked explicitly, then it is the application's responsibility to ensure that all whitespace and metacharacters are quoted appropriately.

Popen Objects

Instances of the :class:`Popen` class have the following methods:

The following attributes are also available:


Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`, :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

Windows Popen Helpers

The :class:`STARTUPINFO` class and following constants are only available on Windows.

Partial support of the Windows STARTUPINFO structure is used for :class:`Popen` creation.


The :mod:`subprocess` module exposes the following constants.

Replacing Older Functions with the :mod:`subprocess` Module

In this section, "a becomes b" means that b can be used as a replacement for a.


All "a" functions in this section fail (more or less) silently if the executed program cannot be found; the "b" replacements raise :exc:`OSError` instead.

In addition, the replacements using :func:`check_output` will fail with a :exc:`CalledProcessError` if the requested operation produces a non-zero return code. The output is still available as the output attribute of the raised exception.

In the following examples, we assume that the relevant functions have already been imported from the :mod:`subprocess` module.

Replacing /bin/sh shell backquote

output=`mycmd myarg`
# becomes
output = check_output(["mycmd", "myarg"])

Replacing shell pipeline

output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.

Alternatively, for trusted input, the shell's own pipeline support may still be used directly:

output=`dmesg | grep hda`
# becomes
output=check_output("dmesg | grep hda", shell=True)

Replacing :func:`os.system`

sts = os.system("mycmd" + " myarg")
# becomes
sts = call("mycmd" + " myarg", shell=True)


  • Calling the program through the shell is usually not required.

A more realistic example would look like this:

    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode, file=sys.stderr)
        print("Child returned", retcode, file=sys.stderr)
except OSError as e:
    print("Execution failed:", e, file=sys.stderr)

Replacing the :func:`os.spawn <os.spawnl>` family

P_NOWAIT example:

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT example:

retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
retcode = call(["/bin/mycmd", "myarg"])

Vector example:

os.spawnvp(os.P_NOWAIT, path, args)
Popen([path] + args[1:])

Environment example:

os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})

Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`

(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
 child_stderr) = os.popen3(cmd, mode, bufsize)
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
 child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

Return code handling translates as follows:

pipe = os.popen(cmd, 'w')
rc = pipe.close()
if rc is not None and rc >> 8:
    print("There were some errors")
process = Popen(cmd, 'w', stdin=PIPE)
if process.wait() != 0:
    print("There were some errors")

Replacing functions from the :mod:`popen2` module


If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed.

(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
p = Popen(["somestring"], shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as :class:`subprocess.Popen`, except that:

  • :class:`Popen` raises an exception if the execution fails.
  • the capturestderr argument is replaced with the stderr argument.
  • stdin=PIPE and stdout=PIPE must be specified.
  • popen2 closes all file descriptors by default, but you have to specify close_fds=True with :class:`Popen` to guarantee this behavior on all platforms or past Python versions.

Legacy Shell Invocation Functions

This module also provides the following legacy functions from the 2.x commands module. These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions.


Converting an argument sequence to a string on Windows

On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):

  1. Arguments are delimited by white space, which is either a space or a tab.
  2. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.
  3. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
  4. Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
  5. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.