blob: 1d87d2f8005ec6554fd276aa4bfe14a9d2c7202a [file] [log] [blame]
Victor Stinner08444382014-02-02 22:43:39 +01001.. currentmodule:: asyncio
2
Victor Stinner778015b2014-07-11 12:13:39 +02003.. _asyncio-subprocess:
4
Yury Selivanov7c7605f2018-09-11 09:54:40 -07005============
6Subprocesses
7============
Victor Stinner08444382014-02-02 22:43:39 +01008
Kyle Stanleyf9000642019-10-10 19:18:46 -04009**Source code:** :source:`Lib/asyncio/subprocess.py`,
10:source:`Lib/asyncio/base_subprocess.py`
11
12----------------------------------------
13
Yury Selivanov7c7605f2018-09-11 09:54:40 -070014This section describes high-level async/await asyncio APIs to
15create and manage subprocesses.
lf627d2c82017-07-25 17:03:51 -060016
Yury Selivanov7372c3b2018-09-14 15:11:24 -070017.. _asyncio_example_subprocess_shell:
18
Yury Selivanov7c7605f2018-09-11 09:54:40 -070019Here's an example of how asyncio can run a shell command and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040020obtain its result::
Victor Stinner984600f2014-03-25 09:40:26 +010021
Yury Selivanov7c7605f2018-09-11 09:54:40 -070022 import asyncio
Victor Stinner984600f2014-03-25 09:40:26 +010023
Yury Selivanov7c7605f2018-09-11 09:54:40 -070024 async def run(cmd):
25 proc = await asyncio.create_subprocess_shell(
26 cmd,
27 stdout=asyncio.subprocess.PIPE,
28 stderr=asyncio.subprocess.PIPE)
Victor Stinneraea82292014-07-08 23:42:38 +020029
Yury Selivanov7c7605f2018-09-11 09:54:40 -070030 stdout, stderr = await proc.communicate()
Victor Stinner984600f2014-03-25 09:40:26 +010031
Yury Selivanov7c7605f2018-09-11 09:54:40 -070032 print(f'[{cmd!r} exited with {proc.returncode}]')
33 if stdout:
34 print(f'[stdout]\n{stdout.decode()}')
35 if stderr:
36 print(f'[stderr]\n{stderr.decode()}')
Victor Stinner778015b2014-07-11 12:13:39 +020037
Yury Selivanov7c7605f2018-09-11 09:54:40 -070038 asyncio.run(run('ls /zzz'))
39
40will print::
41
42 ['ls /zzz' exited with 1]
43 [stderr]
44 ls: /zzz: No such file or directory
45
46Because all asyncio subprocess functions are asynchronous and asyncio
47provides many tools to work with such functions, it is easy to execute
48and monitor multiple subprocesses in parallel. It is indeed trivial
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040049to modify the above example to run several commands simultaneously::
Yury Selivanov7c7605f2018-09-11 09:54:40 -070050
51 async def main():
52 await asyncio.gather(
53 run('ls /zzz'),
54 run('sleep 1; echo "hello"'))
55
56 asyncio.run(main())
57
58See also the `Examples`_ subsection.
Victor Stinner778015b2014-07-11 12:13:39 +020059
Victor Stinner984600f2014-03-25 09:40:26 +010060
Yury Selivanov7c7605f2018-09-11 09:54:40 -070061Creating Subprocesses
62=====================
Victor Stinner08444382014-02-02 22:43:39 +010063
Dima Tisnek13283752019-04-05 23:02:28 +090064.. coroutinefunction:: create_subprocess_exec(program, \*args, stdin=None, \
Yury Selivanov7c7605f2018-09-11 09:54:40 -070065 stdout=None, stderr=None, loop=None, \
66 limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010067
Victor Stinner39892052014-10-14 00:52:07 +020068 Create a subprocess.
Victor Stinner08444382014-02-02 22:43:39 +010069
Yury Selivanov7c7605f2018-09-11 09:54:40 -070070 The *limit* argument sets the buffer limit for :class:`StreamReader`
71 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
Carol Willing4e824e92018-09-13 18:28:19 -070072 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments).
Victor Stinner39892052014-10-14 00:52:07 +020073
74 Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner984600f2014-03-25 09:40:26 +010075
Yury Selivanov7c7605f2018-09-11 09:54:40 -070076 See the documentation of :meth:`loop.subprocess_exec` for other
77 parameters.
Victor Stinner08444382014-02-02 22:43:39 +010078
Andrew Svetlova4888792019-09-12 15:40:40 +030079 .. deprecated-removed:: 3.8 3.10
80
81 The *loop* parameter.
82
Yury Selivanov7c7605f2018-09-11 09:54:40 -070083.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \
84 stdout=None, stderr=None, loop=None, \
85 limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010086
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040087 Run the *cmd* shell command.
Victor Stinner08444382014-02-02 22:43:39 +010088
Yury Selivanov7c7605f2018-09-11 09:54:40 -070089 The *limit* argument sets the buffer limit for :class:`StreamReader`
90 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
Carol Willing4e824e92018-09-13 18:28:19 -070091 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments).
Victor Stinner39892052014-10-14 00:52:07 +020092
93 Return a :class:`~asyncio.subprocess.Process` instance.
94
Yury Selivanov7c7605f2018-09-11 09:54:40 -070095 See the documentation of :meth:`loop.subprocess_shell` for other
96 parameters.
Victor Stinner984600f2014-03-25 09:40:26 +010097
Carol Willing4e824e92018-09-13 18:28:19 -070098.. important::
Victor Stinner984600f2014-03-25 09:40:26 +010099
Victor Stinner39892052014-10-14 00:52:07 +0200100 It is the application's responsibility to ensure that all whitespace and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400101 special characters are quoted appropriately to avoid `shell injection
Georg Brandl5d941342016-02-26 19:37:12 +0100102 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
Victor Stinner39892052014-10-14 00:52:07 +0200103 vulnerabilities. The :func:`shlex.quote` function can be used to properly
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400104 escape whitespace and special shell characters in strings that are going
105 to be used to construct shell commands.
Victor Stinner984600f2014-03-25 09:40:26 +0100106
Andrew Svetlova4888792019-09-12 15:40:40 +0300107 .. deprecated-removed:: 3.8 3.10
108
109 The *loop* parameter.
110
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700111.. note::
112
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400113 The default asyncio event loop implementation on **Windows** does not
114 support subprocesses. Subprocesses are available for Windows if a
115 :class:`ProactorEventLoop` is used.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700116 See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
117 for details.
Victor Stinner984600f2014-03-25 09:40:26 +0100118
Victor Stinner08444382014-02-02 22:43:39 +0100119.. seealso::
120
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400121 asyncio also has the following *low-level* APIs to work with subprocesses:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700122 :meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`,
123 :meth:`loop.connect_read_pipe`, :meth:`loop.connect_write_pipe`,
124 as well as the :ref:`Subprocess Transports <asyncio-subprocess-transports>`
125 and :ref:`Subprocess Protocols <asyncio-subprocess-protocols>`.
Victor Stinner08444382014-02-02 22:43:39 +0100126
127
128Constants
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700129=========
Victor Stinner08444382014-02-02 22:43:39 +0100130
131.. data:: asyncio.subprocess.PIPE
132
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700133 Can be passed to the *stdin*, *stdout* or *stderr* parameters.
134
135 If *PIPE* is passed to *stdin* argument, the
136 :attr:`Process.stdin <asyncio.subprocess.Process.stdin>` attribute
137 will point to a :class:`StreamWriter` instance.
138
139 If *PIPE* is passed to *stdout* or *stderr* arguments, the
140 :attr:`Process.stdout <asyncio.subprocess.Process.stdout>` and
141 :attr:`Process.stderr <asyncio.subprocess.Process.stderr>`
142 attributes will point to :class:`StreamReader` instances.
Victor Stinner08444382014-02-02 22:43:39 +0100143
144.. data:: asyncio.subprocess.STDOUT
145
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400146 Special value that can be used as the *stderr* argument and indicates
147 that standard error should be redirected into standard output.
Victor Stinner08444382014-02-02 22:43:39 +0100148
149.. data:: asyncio.subprocess.DEVNULL
150
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400151 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
152 to process creation functions. It indicates that the special file
153 :data:`os.devnull` will be used for the corresponding subprocess stream.
Victor Stinner08444382014-02-02 22:43:39 +0100154
155
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700156Interacting with Subprocesses
157=============================
158
159Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400160functions return instances of the *Process* class. *Process* is a high-level
161wrapper that allows communicating with subprocesses and watching for
162their completion.
Victor Stinner08444382014-02-02 22:43:39 +0100163
164.. class:: asyncio.subprocess.Process
165
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700166 An object that wraps OS processes created by the
167 :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
168 functions.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100169
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700170 This class is designed to have a similar API to the
171 :class:`subprocess.Popen` class, but there are some
172 notable differences:
Victor Stinnerb79eb052014-02-03 23:08:14 +0100173
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700174 * unlike Popen, Process instances do not have an equivalent to
175 the :meth:`~subprocess.Popen.poll` method;
Victor Stinnerb79eb052014-02-03 23:08:14 +0100176
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700177 * the :meth:`~asyncio.subprocess.Process.communicate` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400178 :meth:`~asyncio.subprocess.Process.wait` methods don't have a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700179 *timeout* parameter: use the :func:`wait_for` function;
180
181 * the :meth:`Process.wait() <asyncio.subprocess.Process.wait>` method
182 is asynchronous, whereas :meth:`subprocess.Popen.wait` method
183 is implemented as a blocking busy loop;
184
185 * the *universal_newlines* parameter is not supported.
186
187 This class is :ref:`not thread safe <asyncio-multithreading>`.
188
189 See also the :ref:`Subprocess and Threads <asyncio-subprocess-threads>`
190 section.
Victor Stinner83704962015-02-25 14:24:15 +0100191
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100192 .. coroutinemethod:: wait()
Victor Stinnerb79eb052014-02-03 23:08:14 +0100193
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400194 Wait for the child process to terminate.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100195
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700196 Set and return the :attr:`returncode` attribute.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100197
Victor Stinner39892052014-10-14 00:52:07 +0200198 .. note::
Victor Stinner08444382014-02-02 22:43:39 +0100199
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700200 This method can deadlock when using ``stdout=PIPE`` or
201 ``stderr=PIPE`` and the child process generates so much output
202 that it blocks waiting for the OS pipe buffer to accept
203 more data. Use the :meth:`communicate` method when using pipes
204 to avoid this condition.
Victor Stinner08444382014-02-02 22:43:39 +0100205
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100206 .. coroutinemethod:: communicate(input=None)
Victor Stinner08444382014-02-02 22:43:39 +0100207
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700208 Interact with process:
Victor Stinner08444382014-02-02 22:43:39 +0100209
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700210 1. send data to *stdin* (if *input* is not ``None``);
211 2. read data from *stdout* and *stderr*, until EOF is reached;
212 3. wait for process to terminate.
Victor Stinner39892052014-10-14 00:52:07 +0200213
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700214 The optional *input* argument is the data (:class:`bytes` object)
215 that will be sent to the child process.
Victor Stinnercc996b52014-07-17 12:25:27 +0200216
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700217 Return a tuple ``(stdout_data, stderr_data)``.
Victor Stinner08444382014-02-02 22:43:39 +0100218
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700219 If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError`
220 exception is raised when writing *input* into *stdin*, the
221 exception is ignored. This condition occurs when the process
222 exits before all data are written into *stdin*.
Victor Stinner39892052014-10-14 00:52:07 +0200223
Carol Willing4e824e92018-09-13 18:28:19 -0700224 If it is desired to send data to the process' *stdin*,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700225 the process needs to be created with ``stdin=PIPE``. Similarly,
226 to get anything other than ``None`` in the result tuple, the
227 process has to be created with ``stdout=PIPE`` and/or
228 ``stderr=PIPE`` arguments.
Victor Stinner08444382014-02-02 22:43:39 +0100229
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700230 Note, that the data read is buffered in memory, so do not use
231 this method if the data size is large or unlimited.
Victor Stinnercc996b52014-07-17 12:25:27 +0200232
Brian Curtina1afeec2014-02-08 18:36:14 -0600233 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100234
235 Sends the signal *signal* to the child process.
236
237 .. note::
238
239 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
240 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
241 started with a *creationflags* parameter which includes
242 ``CREATE_NEW_PROCESS_GROUP``.
243
244 .. method:: terminate()
245
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400246 Stop the child process.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700247
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400248 On POSIX systems this method sends :py:data:`signal.SIGTERM` to the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700249 child process.
250
251 On Windows the Win32 API function :c:func:`TerminateProcess` is
252 called to stop the child process.
Victor Stinner08444382014-02-02 22:43:39 +0100253
Victor Stinner39892052014-10-14 00:52:07 +0200254 .. method:: kill()
Victor Stinner08444382014-02-02 22:43:39 +0100255
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700256 Kill the child.
257
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400258 On POSIX systems this method sends :py:data:`SIGKILL` to the child
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700259 process.
260
261 On Windows this method is an alias for :meth:`terminate`.
Victor Stinner08444382014-02-02 22:43:39 +0100262
Victor Stinner39892052014-10-14 00:52:07 +0200263 .. attribute:: stdin
264
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700265 Standard input stream (:class:`StreamWriter`) or ``None``
266 if the process was created with ``stdin=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200267
268 .. attribute:: stdout
269
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700270 Standard output stream (:class:`StreamReader`) or ``None``
271 if the process was created with ``stdout=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200272
273 .. attribute:: stderr
274
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700275 Standard error stream (:class:`StreamReader`) or ``None``
276 if the process was created with ``stderr=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200277
278 .. warning::
279
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700280 Use the :meth:`communicate` method rather than
281 :attr:`process.stdin.write() <stdin>`,
282 :attr:`await process.stdout.read() <stdout>` or
Carol Willing4e824e92018-09-13 18:28:19 -0700283 :attr:`await process.stderr.read <stderr>`.
284 This avoids deadlocks due to streams pausing reading or writing
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700285 and blocking the child process.
Victor Stinner39892052014-10-14 00:52:07 +0200286
287 .. attribute:: pid
288
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700289 Process identification number (PID).
Victor Stinner39892052014-10-14 00:52:07 +0200290
291 Note that for processes created by the :func:`create_subprocess_shell`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700292 function, this attribute is the PID of the spawned shell.
Victor Stinner39892052014-10-14 00:52:07 +0200293
294 .. attribute:: returncode
295
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700296 Return code of the process when it exits.
Victor Stinner39892052014-10-14 00:52:07 +0200297
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700298 A ``None`` value indicates that the process has not terminated yet.
299
300 A negative value ``-N`` indicates that the child was terminated
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400301 by signal ``N`` (POSIX only).
Victor Stinner7bdf7862014-03-16 21:29:31 +0100302
Victor Stinnere48d4db2014-02-03 23:26:28 +0100303
Victor Stinner399c59d2015-01-09 01:32:02 +0100304.. _asyncio-subprocess-threads:
305
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700306Subprocess and Threads
Victor Stinner5492d352015-09-02 15:39:01 +0200307----------------------
Victor Stinner399c59d2015-01-09 01:32:02 +0100308
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300309Standard asyncio event loop supports running subprocesses from different threads by
310default.
Victor Stinner399c59d2015-01-09 01:32:02 +0100311
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300312On Windows subprocesses are provided by :class:`ProactorEventLoop` only (default),
313:class:`SelectorEventLoop` has no subprocess support.
Victor Stinner399c59d2015-01-09 01:32:02 +0100314
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300315On UNIX *child watchers* are used for subprocess finish waiting, see
316:ref:`asyncio-watchers` for more info.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700317
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300318
319.. versionchanged:: 3.8
320
321 UNIX switched to use :class:`ThreadedChildWatcher` for spawning subprocesses from
322 different threads without any limitation.
323
324 Spawning a subprocess with *inactive* current child watcher raises
325 :exc:`RuntimeError`.
326
327Note that alternative event loop implementations might have own limitations;
328please refer to their documentation.
Victor Stinner83704962015-02-25 14:24:15 +0100329
Victor Stinner399c59d2015-01-09 01:32:02 +0100330.. seealso::
331
332 The :ref:`Concurrency and multithreading in asyncio
333 <asyncio-multithreading>` section.
334
335
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700336Examples
337--------
Victor Stinnere48d4db2014-02-03 23:26:28 +0100338
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700339An example using the :class:`~asyncio.subprocess.Process` class to
340control a subprocess and the :class:`StreamReader` class to read from
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400341its standard output.
Victor Stinner39892052014-10-14 00:52:07 +0200342
Yury Selivanov394374e2018-09-17 15:35:24 -0400343.. _asyncio_example_create_subprocess_exec:
344
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700345The subprocess is created by the :func:`create_subprocess_exec`
Victor Stinner39892052014-10-14 00:52:07 +0200346function::
347
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700348 import asyncio
Victor Stinner39892052014-10-14 00:52:07 +0200349 import sys
350
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400351 async def get_date():
Victor Stinner39892052014-10-14 00:52:07 +0200352 code = 'import datetime; print(datetime.datetime.now())'
353
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700354 # Create the subprocess; redirect the standard output
355 # into a pipe.
Andrew Svetlov88743422017-12-11 17:35:49 +0200356 proc = await asyncio.create_subprocess_exec(
357 sys.executable, '-c', code,
358 stdout=asyncio.subprocess.PIPE)
Victor Stinner39892052014-10-14 00:52:07 +0200359
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700360 # Read one line of output.
Andrew Svetlov88743422017-12-11 17:35:49 +0200361 data = await proc.stdout.readline()
Victor Stinner39892052014-10-14 00:52:07 +0200362 line = data.decode('ascii').rstrip()
363
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700364 # Wait for the subprocess exit.
Andrew Svetlov88743422017-12-11 17:35:49 +0200365 await proc.wait()
Victor Stinner39892052014-10-14 00:52:07 +0200366 return line
367
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700368 date = asyncio.run(get_date())
369 print(f"Current date: {date}")
370
371
Yury Selivanov394374e2018-09-17 15:35:24 -0400372See also the :ref:`same example <asyncio_example_subprocess_proto>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700373written using low-level APIs.