blob: bd92257c82efa2ba4d4107ca701da83c6592f758 [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
Yury Selivanov7c7605f2018-09-11 09:54:40 -07009This section describes high-level async/await asyncio APIs to
10create and manage subprocesses.
lf627d2c82017-07-25 17:03:51 -060011
Yury Selivanov7372c3b2018-09-14 15:11:24 -070012.. _asyncio_example_subprocess_shell:
13
Yury Selivanov7c7605f2018-09-11 09:54:40 -070014Here's an example of how asyncio can run a shell command and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040015obtain its result::
Victor Stinner984600f2014-03-25 09:40:26 +010016
Yury Selivanov7c7605f2018-09-11 09:54:40 -070017 import asyncio
Victor Stinner984600f2014-03-25 09:40:26 +010018
Yury Selivanov7c7605f2018-09-11 09:54:40 -070019 async def run(cmd):
20 proc = await asyncio.create_subprocess_shell(
21 cmd,
22 stdout=asyncio.subprocess.PIPE,
23 stderr=asyncio.subprocess.PIPE)
Victor Stinneraea82292014-07-08 23:42:38 +020024
Yury Selivanov7c7605f2018-09-11 09:54:40 -070025 stdout, stderr = await proc.communicate()
Victor Stinner984600f2014-03-25 09:40:26 +010026
Yury Selivanov7c7605f2018-09-11 09:54:40 -070027 print(f'[{cmd!r} exited with {proc.returncode}]')
28 if stdout:
29 print(f'[stdout]\n{stdout.decode()}')
30 if stderr:
31 print(f'[stderr]\n{stderr.decode()}')
Victor Stinner778015b2014-07-11 12:13:39 +020032
Yury Selivanov7c7605f2018-09-11 09:54:40 -070033 asyncio.run(run('ls /zzz'))
34
35will print::
36
37 ['ls /zzz' exited with 1]
38 [stderr]
39 ls: /zzz: No such file or directory
40
41Because all asyncio subprocess functions are asynchronous and asyncio
42provides many tools to work with such functions, it is easy to execute
43and monitor multiple subprocesses in parallel. It is indeed trivial
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040044to modify the above example to run several commands simultaneously::
Yury Selivanov7c7605f2018-09-11 09:54:40 -070045
46 async def main():
47 await asyncio.gather(
48 run('ls /zzz'),
49 run('sleep 1; echo "hello"'))
50
51 asyncio.run(main())
52
53See also the `Examples`_ subsection.
Victor Stinner778015b2014-07-11 12:13:39 +020054
Victor Stinner984600f2014-03-25 09:40:26 +010055
Yury Selivanov7c7605f2018-09-11 09:54:40 -070056Creating Subprocesses
57=====================
Victor Stinner08444382014-02-02 22:43:39 +010058
Dima Tisnek13283752019-04-05 23:02:28 +090059.. coroutinefunction:: create_subprocess_exec(program, \*args, stdin=None, \
Yury Selivanov7c7605f2018-09-11 09:54:40 -070060 stdout=None, stderr=None, loop=None, \
61 limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010062
Victor Stinner39892052014-10-14 00:52:07 +020063 Create a subprocess.
Victor Stinner08444382014-02-02 22:43:39 +010064
Yury Selivanov7c7605f2018-09-11 09:54:40 -070065 The *limit* argument sets the buffer limit for :class:`StreamReader`
66 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
Carol Willing4e824e92018-09-13 18:28:19 -070067 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments).
Victor Stinner39892052014-10-14 00:52:07 +020068
69 Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner984600f2014-03-25 09:40:26 +010070
Yury Selivanov7c7605f2018-09-11 09:54:40 -070071 See the documentation of :meth:`loop.subprocess_exec` for other
72 parameters.
Victor Stinner08444382014-02-02 22:43:39 +010073
Andrew Svetlova4888792019-09-12 15:40:40 +030074 .. deprecated-removed:: 3.8 3.10
75
76 The *loop* parameter.
77
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \
79 stdout=None, stderr=None, loop=None, \
80 limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010081
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040082 Run the *cmd* shell command.
Victor Stinner08444382014-02-02 22:43:39 +010083
Yury Selivanov7c7605f2018-09-11 09:54:40 -070084 The *limit* argument sets the buffer limit for :class:`StreamReader`
85 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
Carol Willing4e824e92018-09-13 18:28:19 -070086 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments).
Victor Stinner39892052014-10-14 00:52:07 +020087
88 Return a :class:`~asyncio.subprocess.Process` instance.
89
Yury Selivanov7c7605f2018-09-11 09:54:40 -070090 See the documentation of :meth:`loop.subprocess_shell` for other
91 parameters.
Victor Stinner984600f2014-03-25 09:40:26 +010092
Carol Willing4e824e92018-09-13 18:28:19 -070093.. important::
Victor Stinner984600f2014-03-25 09:40:26 +010094
Victor Stinner39892052014-10-14 00:52:07 +020095 It is the application's responsibility to ensure that all whitespace and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040096 special characters are quoted appropriately to avoid `shell injection
Georg Brandl5d941342016-02-26 19:37:12 +010097 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
Victor Stinner39892052014-10-14 00:52:07 +020098 vulnerabilities. The :func:`shlex.quote` function can be used to properly
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040099 escape whitespace and special shell characters in strings that are going
100 to be used to construct shell commands.
Victor Stinner984600f2014-03-25 09:40:26 +0100101
Andrew Svetlova4888792019-09-12 15:40:40 +0300102 .. deprecated-removed:: 3.8 3.10
103
104 The *loop* parameter.
105
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700106.. note::
107
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400108 The default asyncio event loop implementation on **Windows** does not
109 support subprocesses. Subprocesses are available for Windows if a
110 :class:`ProactorEventLoop` is used.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700111 See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
112 for details.
Victor Stinner984600f2014-03-25 09:40:26 +0100113
Victor Stinner08444382014-02-02 22:43:39 +0100114.. seealso::
115
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400116 asyncio also has the following *low-level* APIs to work with subprocesses:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700117 :meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`,
118 :meth:`loop.connect_read_pipe`, :meth:`loop.connect_write_pipe`,
119 as well as the :ref:`Subprocess Transports <asyncio-subprocess-transports>`
120 and :ref:`Subprocess Protocols <asyncio-subprocess-protocols>`.
Victor Stinner08444382014-02-02 22:43:39 +0100121
122
123Constants
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700124=========
Victor Stinner08444382014-02-02 22:43:39 +0100125
126.. data:: asyncio.subprocess.PIPE
127
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700128 Can be passed to the *stdin*, *stdout* or *stderr* parameters.
129
130 If *PIPE* is passed to *stdin* argument, the
131 :attr:`Process.stdin <asyncio.subprocess.Process.stdin>` attribute
132 will point to a :class:`StreamWriter` instance.
133
134 If *PIPE* is passed to *stdout* or *stderr* arguments, the
135 :attr:`Process.stdout <asyncio.subprocess.Process.stdout>` and
136 :attr:`Process.stderr <asyncio.subprocess.Process.stderr>`
137 attributes will point to :class:`StreamReader` instances.
Victor Stinner08444382014-02-02 22:43:39 +0100138
139.. data:: asyncio.subprocess.STDOUT
140
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400141 Special value that can be used as the *stderr* argument and indicates
142 that standard error should be redirected into standard output.
Victor Stinner08444382014-02-02 22:43:39 +0100143
144.. data:: asyncio.subprocess.DEVNULL
145
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400146 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
147 to process creation functions. It indicates that the special file
148 :data:`os.devnull` will be used for the corresponding subprocess stream.
Victor Stinner08444382014-02-02 22:43:39 +0100149
150
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700151Interacting with Subprocesses
152=============================
153
154Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400155functions return instances of the *Process* class. *Process* is a high-level
156wrapper that allows communicating with subprocesses and watching for
157their completion.
Victor Stinner08444382014-02-02 22:43:39 +0100158
159.. class:: asyncio.subprocess.Process
160
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700161 An object that wraps OS processes created by the
162 :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
163 functions.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100164
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700165 This class is designed to have a similar API to the
166 :class:`subprocess.Popen` class, but there are some
167 notable differences:
Victor Stinnerb79eb052014-02-03 23:08:14 +0100168
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700169 * unlike Popen, Process instances do not have an equivalent to
170 the :meth:`~subprocess.Popen.poll` method;
Victor Stinnerb79eb052014-02-03 23:08:14 +0100171
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700172 * the :meth:`~asyncio.subprocess.Process.communicate` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400173 :meth:`~asyncio.subprocess.Process.wait` methods don't have a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700174 *timeout* parameter: use the :func:`wait_for` function;
175
176 * the :meth:`Process.wait() <asyncio.subprocess.Process.wait>` method
177 is asynchronous, whereas :meth:`subprocess.Popen.wait` method
178 is implemented as a blocking busy loop;
179
180 * the *universal_newlines* parameter is not supported.
181
182 This class is :ref:`not thread safe <asyncio-multithreading>`.
183
184 See also the :ref:`Subprocess and Threads <asyncio-subprocess-threads>`
185 section.
Victor Stinner83704962015-02-25 14:24:15 +0100186
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100187 .. coroutinemethod:: wait()
Victor Stinnerb79eb052014-02-03 23:08:14 +0100188
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400189 Wait for the child process to terminate.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100190
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700191 Set and return the :attr:`returncode` attribute.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100192
Victor Stinner39892052014-10-14 00:52:07 +0200193 .. note::
Victor Stinner08444382014-02-02 22:43:39 +0100194
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700195 This method can deadlock when using ``stdout=PIPE`` or
196 ``stderr=PIPE`` and the child process generates so much output
197 that it blocks waiting for the OS pipe buffer to accept
198 more data. Use the :meth:`communicate` method when using pipes
199 to avoid this condition.
Victor Stinner08444382014-02-02 22:43:39 +0100200
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100201 .. coroutinemethod:: communicate(input=None)
Victor Stinner08444382014-02-02 22:43:39 +0100202
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700203 Interact with process:
Victor Stinner08444382014-02-02 22:43:39 +0100204
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700205 1. send data to *stdin* (if *input* is not ``None``);
206 2. read data from *stdout* and *stderr*, until EOF is reached;
207 3. wait for process to terminate.
Victor Stinner39892052014-10-14 00:52:07 +0200208
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700209 The optional *input* argument is the data (:class:`bytes` object)
210 that will be sent to the child process.
Victor Stinnercc996b52014-07-17 12:25:27 +0200211
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700212 Return a tuple ``(stdout_data, stderr_data)``.
Victor Stinner08444382014-02-02 22:43:39 +0100213
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700214 If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError`
215 exception is raised when writing *input* into *stdin*, the
216 exception is ignored. This condition occurs when the process
217 exits before all data are written into *stdin*.
Victor Stinner39892052014-10-14 00:52:07 +0200218
Carol Willing4e824e92018-09-13 18:28:19 -0700219 If it is desired to send data to the process' *stdin*,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700220 the process needs to be created with ``stdin=PIPE``. Similarly,
221 to get anything other than ``None`` in the result tuple, the
222 process has to be created with ``stdout=PIPE`` and/or
223 ``stderr=PIPE`` arguments.
Victor Stinner08444382014-02-02 22:43:39 +0100224
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700225 Note, that the data read is buffered in memory, so do not use
226 this method if the data size is large or unlimited.
Victor Stinnercc996b52014-07-17 12:25:27 +0200227
Brian Curtina1afeec2014-02-08 18:36:14 -0600228 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100229
230 Sends the signal *signal* to the child process.
231
232 .. note::
233
234 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
235 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
236 started with a *creationflags* parameter which includes
237 ``CREATE_NEW_PROCESS_GROUP``.
238
239 .. method:: terminate()
240
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400241 Stop the child process.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700242
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400243 On POSIX systems this method sends :py:data:`signal.SIGTERM` to the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700244 child process.
245
246 On Windows the Win32 API function :c:func:`TerminateProcess` is
247 called to stop the child process.
Victor Stinner08444382014-02-02 22:43:39 +0100248
Victor Stinner39892052014-10-14 00:52:07 +0200249 .. method:: kill()
Victor Stinner08444382014-02-02 22:43:39 +0100250
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700251 Kill the child.
252
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400253 On POSIX systems this method sends :py:data:`SIGKILL` to the child
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700254 process.
255
256 On Windows this method is an alias for :meth:`terminate`.
Victor Stinner08444382014-02-02 22:43:39 +0100257
Victor Stinner39892052014-10-14 00:52:07 +0200258 .. attribute:: stdin
259
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700260 Standard input stream (:class:`StreamWriter`) or ``None``
261 if the process was created with ``stdin=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200262
263 .. attribute:: stdout
264
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700265 Standard output stream (:class:`StreamReader`) or ``None``
266 if the process was created with ``stdout=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200267
268 .. attribute:: stderr
269
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700270 Standard error stream (:class:`StreamReader`) or ``None``
271 if the process was created with ``stderr=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200272
273 .. warning::
274
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700275 Use the :meth:`communicate` method rather than
276 :attr:`process.stdin.write() <stdin>`,
277 :attr:`await process.stdout.read() <stdout>` or
Carol Willing4e824e92018-09-13 18:28:19 -0700278 :attr:`await process.stderr.read <stderr>`.
279 This avoids deadlocks due to streams pausing reading or writing
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700280 and blocking the child process.
Victor Stinner39892052014-10-14 00:52:07 +0200281
282 .. attribute:: pid
283
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700284 Process identification number (PID).
Victor Stinner39892052014-10-14 00:52:07 +0200285
286 Note that for processes created by the :func:`create_subprocess_shell`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700287 function, this attribute is the PID of the spawned shell.
Victor Stinner39892052014-10-14 00:52:07 +0200288
289 .. attribute:: returncode
290
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700291 Return code of the process when it exits.
Victor Stinner39892052014-10-14 00:52:07 +0200292
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700293 A ``None`` value indicates that the process has not terminated yet.
294
295 A negative value ``-N`` indicates that the child was terminated
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400296 by signal ``N`` (POSIX only).
Victor Stinner7bdf7862014-03-16 21:29:31 +0100297
Victor Stinnere48d4db2014-02-03 23:26:28 +0100298
Victor Stinner399c59d2015-01-09 01:32:02 +0100299.. _asyncio-subprocess-threads:
300
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700301Subprocess and Threads
Victor Stinner5492d352015-09-02 15:39:01 +0200302----------------------
Victor Stinner399c59d2015-01-09 01:32:02 +0100303
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300304Standard asyncio event loop supports running subprocesses from different threads by
305default.
Victor Stinner399c59d2015-01-09 01:32:02 +0100306
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300307On Windows subprocesses are provided by :class:`ProactorEventLoop` only (default),
308:class:`SelectorEventLoop` has no subprocess support.
Victor Stinner399c59d2015-01-09 01:32:02 +0100309
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300310On UNIX *child watchers* are used for subprocess finish waiting, see
311:ref:`asyncio-watchers` for more info.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700312
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300313
314.. versionchanged:: 3.8
315
316 UNIX switched to use :class:`ThreadedChildWatcher` for spawning subprocesses from
317 different threads without any limitation.
318
319 Spawning a subprocess with *inactive* current child watcher raises
320 :exc:`RuntimeError`.
321
322Note that alternative event loop implementations might have own limitations;
323please refer to their documentation.
Victor Stinner83704962015-02-25 14:24:15 +0100324
Victor Stinner399c59d2015-01-09 01:32:02 +0100325.. seealso::
326
327 The :ref:`Concurrency and multithreading in asyncio
328 <asyncio-multithreading>` section.
329
330
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700331Examples
332--------
Victor Stinnere48d4db2014-02-03 23:26:28 +0100333
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700334An example using the :class:`~asyncio.subprocess.Process` class to
335control a subprocess and the :class:`StreamReader` class to read from
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400336its standard output.
Victor Stinner39892052014-10-14 00:52:07 +0200337
Yury Selivanov394374e2018-09-17 15:35:24 -0400338.. _asyncio_example_create_subprocess_exec:
339
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700340The subprocess is created by the :func:`create_subprocess_exec`
Victor Stinner39892052014-10-14 00:52:07 +0200341function::
342
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700343 import asyncio
Victor Stinner39892052014-10-14 00:52:07 +0200344 import sys
345
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400346 async def get_date():
Victor Stinner39892052014-10-14 00:52:07 +0200347 code = 'import datetime; print(datetime.datetime.now())'
348
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700349 # Create the subprocess; redirect the standard output
350 # into a pipe.
Andrew Svetlov88743422017-12-11 17:35:49 +0200351 proc = await asyncio.create_subprocess_exec(
352 sys.executable, '-c', code,
353 stdout=asyncio.subprocess.PIPE)
Victor Stinner39892052014-10-14 00:52:07 +0200354
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700355 # Read one line of output.
Andrew Svetlov88743422017-12-11 17:35:49 +0200356 data = await proc.stdout.readline()
Victor Stinner39892052014-10-14 00:52:07 +0200357 line = data.decode('ascii').rstrip()
358
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700359 # Wait for the subprocess exit.
Andrew Svetlov88743422017-12-11 17:35:49 +0200360 await proc.wait()
Victor Stinner39892052014-10-14 00:52:07 +0200361 return line
362
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700363 date = asyncio.run(get_date())
364 print(f"Current date: {date}")
365
366
Yury Selivanov394374e2018-09-17 15:35:24 -0400367See also the :ref:`same example <asyncio_example_subprocess_proto>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700368written using low-level APIs.