blob: 0bcf66175ce383460fc41e5aa632bd2e978460f2 [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 Selivanov512d7102018-09-17 19:35:30 -04005============
6Subprocesses
7============
Victor Stinner08444382014-02-02 22:43:39 +01008
Yury Selivanov512d7102018-09-17 19:35:30 -04009This section describes high-level async/await asyncio APIs to
10create and manage subprocesses.
lf627d2c82017-07-25 17:03:51 -060011
Yury Selivanov512d7102018-09-17 19:35:30 -040012.. _asyncio_example_subprocess_shell:
Victor Stinner984600f2014-03-25 09:40:26 +010013
Yury Selivanov512d7102018-09-17 19:35:30 -040014Here's an example of how asyncio can run a shell command and
15obtain its result::
Victor Stinner984600f2014-03-25 09:40:26 +010016
Yury Selivanov512d7102018-09-17 19:35:30 -040017 import asyncio
Victor Stinneraea82292014-07-08 23:42:38 +020018
Yury Selivanov512d7102018-09-17 19:35:30 -040019 async def run(cmd):
20 proc = await asyncio.create_subprocess_shell(
21 cmd,
22 stdout=asyncio.subprocess.PIPE,
23 stderr=asyncio.subprocess.PIPE)
Victor Stinner984600f2014-03-25 09:40:26 +010024
Yury Selivanov512d7102018-09-17 19:35:30 -040025 stdout, stderr = await proc.communicate()
Victor Stinner778015b2014-07-11 12:13:39 +020026
Yury Selivanov512d7102018-09-17 19:35:30 -040027 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()}')
32
33 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
44to modify the above example to run several commands simultaneously::
45
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 Selivanov512d7102018-09-17 19:35:30 -040056Creating Subprocesses
57=====================
Victor Stinner08444382014-02-02 22:43:39 +010058
Yury Selivanov512d7102018-09-17 19:35:30 -040059.. coroutinefunction:: create_subprocess_exec(\*args, stdin=None, \
60 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 Selivanov512d7102018-09-17 19:35:30 -040065 The *limit* argument sets the buffer limit for :class:`StreamReader`
66 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
67 (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 Selivanov512d7102018-09-17 19:35:30 -040071 See the documentation of :meth:`loop.subprocess_exec` for other
Victor Stinner39892052014-10-14 00:52:07 +020072 parameters.
73
Yury Selivanov512d7102018-09-17 19:35:30 -040074.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \
75 stdout=None, stderr=None, loop=None, \
76 limit=None, \*\*kwds)
77
78 Run the *cmd* shell command.
79
80 The *limit* argument sets the buffer limit for :class:`StreamReader`
81 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
82 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments).
83
Victor Stinner39892052014-10-14 00:52:07 +020084 Return a :class:`~asyncio.subprocess.Process` instance.
85
Yury Selivanov512d7102018-09-17 19:35:30 -040086 See the documentation of :meth:`loop.subprocess_shell` for other
87 parameters.
Victor Stinner984600f2014-03-25 09:40:26 +010088
Yury Selivanov512d7102018-09-17 19:35:30 -040089.. important::
Victor Stinner984600f2014-03-25 09:40:26 +010090
Victor Stinner39892052014-10-14 00:52:07 +020091 It is the application's responsibility to ensure that all whitespace and
Yury Selivanov512d7102018-09-17 19:35:30 -040092 special characters are quoted appropriately to avoid `shell injection
Georg Brandl5d941342016-02-26 19:37:12 +010093 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
Victor Stinner39892052014-10-14 00:52:07 +020094 vulnerabilities. The :func:`shlex.quote` function can be used to properly
Yury Selivanov512d7102018-09-17 19:35:30 -040095 escape whitespace and special shell characters in strings that are going
96 to be used to construct shell commands.
Victor Stinner984600f2014-03-25 09:40:26 +010097
Yury Selivanov512d7102018-09-17 19:35:30 -040098.. note::
99
100 The default asyncio event loop implementation on **Windows** does not
101 support subprocesses. Subprocesses are available for Windows if a
102 :class:`ProactorEventLoop` is used.
103 See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
104 for details.
Victor Stinner984600f2014-03-25 09:40:26 +0100105
Victor Stinner08444382014-02-02 22:43:39 +0100106.. seealso::
107
Yury Selivanov512d7102018-09-17 19:35:30 -0400108 asyncio also has the following *low-level* APIs to work with subprocesses:
109 :meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`,
110 :meth:`loop.connect_read_pipe`, :meth:`loop.connect_write_pipe`,
111 as well as the :ref:`Subprocess Transports <asyncio-subprocess-transports>`
112 and :ref:`Subprocess Protocols <asyncio-subprocess-protocols>`.
Victor Stinner08444382014-02-02 22:43:39 +0100113
114
115Constants
Yury Selivanov512d7102018-09-17 19:35:30 -0400116=========
Victor Stinner08444382014-02-02 22:43:39 +0100117
118.. data:: asyncio.subprocess.PIPE
119
Yury Selivanov512d7102018-09-17 19:35:30 -0400120 Can be passed to the *stdin*, *stdout* or *stderr* parameters.
121
122 If *PIPE* is passed to *stdin* argument, the
123 :attr:`Process.stdin <asyncio.subprocess.Process.stdin>` attribute
124 will point to a :class:`StreamWriter` instance.
125
126 If *PIPE* is passed to *stdout* or *stderr* arguments, the
127 :attr:`Process.stdout <asyncio.subprocess.Process.stdout>` and
128 :attr:`Process.stderr <asyncio.subprocess.Process.stderr>`
129 attributes will point to :class:`StreamReader` instances.
Victor Stinner08444382014-02-02 22:43:39 +0100130
131.. data:: asyncio.subprocess.STDOUT
132
Yury Selivanov512d7102018-09-17 19:35:30 -0400133 Special value that can be used as the *stderr* argument and indicates
134 that standard error should be redirected into standard output.
Victor Stinner08444382014-02-02 22:43:39 +0100135
136.. data:: asyncio.subprocess.DEVNULL
137
Victor Stinner72804862014-03-21 11:44:49 +0100138 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
Yury Selivanov512d7102018-09-17 19:35:30 -0400139 to process creation functions. It indicates that the special file
140 :data:`os.devnull` will be used for the corresponding subprocess stream.
Victor Stinner08444382014-02-02 22:43:39 +0100141
142
Yury Selivanov512d7102018-09-17 19:35:30 -0400143Interacting with Subprocesses
144=============================
145
146Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
147functions return instances of the *Process* class. *Process* is a high-level
148wrapper that allows communicating with subprocesses and watching for
149their completion.
Victor Stinner08444382014-02-02 22:43:39 +0100150
151.. class:: asyncio.subprocess.Process
152
Yury Selivanov512d7102018-09-17 19:35:30 -0400153 An object that wraps OS processes created by the
154 :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
155 functions.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100156
Yury Selivanov512d7102018-09-17 19:35:30 -0400157 This class is designed to have a similar API to the
158 :class:`subprocess.Popen` class, but there are some
159 notable differences:
Victor Stinnerb79eb052014-02-03 23:08:14 +0100160
Yury Selivanov512d7102018-09-17 19:35:30 -0400161 * unlike Popen, Process instances do not have an equivalent to
162 the :meth:`~subprocess.Popen.poll` method;
Victor Stinnerb79eb052014-02-03 23:08:14 +0100163
Yury Selivanov512d7102018-09-17 19:35:30 -0400164 * the :meth:`~asyncio.subprocess.Process.communicate` and
165 :meth:`~asyncio.subprocess.Process.wait` methods don't have a
166 *timeout* parameter: use the :func:`wait_for` function;
167
168 * the :meth:`Process.wait() <asyncio.subprocess.Process.wait>` method
169 is asynchronous, whereas :meth:`subprocess.Popen.wait` method
170 is implemented as a blocking busy loop;
171
172 * the *universal_newlines* parameter is not supported.
173
174 This class is :ref:`not thread safe <asyncio-multithreading>`.
175
176 See also the :ref:`Subprocess and Threads <asyncio-subprocess-threads>`
177 section.
Victor Stinner83704962015-02-25 14:24:15 +0100178
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100179 .. coroutinemethod:: wait()
Victor Stinnerb79eb052014-02-03 23:08:14 +0100180
Yury Selivanov512d7102018-09-17 19:35:30 -0400181 Wait for the child process to terminate.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100182
Yury Selivanov512d7102018-09-17 19:35:30 -0400183 Set and return the :attr:`returncode` attribute.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100184
Victor Stinner39892052014-10-14 00:52:07 +0200185 .. note::
Victor Stinner08444382014-02-02 22:43:39 +0100186
Yury Selivanov512d7102018-09-17 19:35:30 -0400187 This method can deadlock when using ``stdout=PIPE`` or
188 ``stderr=PIPE`` and the child process generates so much output
189 that it blocks waiting for the OS pipe buffer to accept
190 more data. Use the :meth:`communicate` method when using pipes
191 to avoid this condition.
Victor Stinner08444382014-02-02 22:43:39 +0100192
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100193 .. coroutinemethod:: communicate(input=None)
Victor Stinner08444382014-02-02 22:43:39 +0100194
Yury Selivanov512d7102018-09-17 19:35:30 -0400195 Interact with process:
Victor Stinner08444382014-02-02 22:43:39 +0100196
Yury Selivanov512d7102018-09-17 19:35:30 -0400197 1. send data to *stdin* (if *input* is not ``None``);
198 2. read data from *stdout* and *stderr*, until EOF is reached;
199 3. wait for process to terminate.
Victor Stinner39892052014-10-14 00:52:07 +0200200
Yury Selivanov512d7102018-09-17 19:35:30 -0400201 The optional *input* argument is the data (:class:`bytes` object)
202 that will be sent to the child process.
Victor Stinnercc996b52014-07-17 12:25:27 +0200203
Yury Selivanov512d7102018-09-17 19:35:30 -0400204 Return a tuple ``(stdout_data, stderr_data)``.
Victor Stinner08444382014-02-02 22:43:39 +0100205
Yury Selivanov512d7102018-09-17 19:35:30 -0400206 If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError`
207 exception is raised when writing *input* into *stdin*, the
208 exception is ignored. This condition occurs when the process
209 exits before all data are written into *stdin*.
Victor Stinner39892052014-10-14 00:52:07 +0200210
Yury Selivanov512d7102018-09-17 19:35:30 -0400211 If it is desired to send data to the process' *stdin*,
212 the process needs to be created with ``stdin=PIPE``. Similarly,
213 to get anything other than ``None`` in the result tuple, the
214 process has to be created with ``stdout=PIPE`` and/or
215 ``stderr=PIPE`` arguments.
Victor Stinner08444382014-02-02 22:43:39 +0100216
Yury Selivanov512d7102018-09-17 19:35:30 -0400217 Note, that the data read is buffered in memory, so do not use
218 this method if the data size is large or unlimited.
Victor Stinnercc996b52014-07-17 12:25:27 +0200219
Brian Curtina1afeec2014-02-08 18:36:14 -0600220 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100221
222 Sends the signal *signal* to the child process.
223
224 .. note::
225
226 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
227 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
228 started with a *creationflags* parameter which includes
229 ``CREATE_NEW_PROCESS_GROUP``.
230
231 .. method:: terminate()
232
Yury Selivanov512d7102018-09-17 19:35:30 -0400233 Stop the child process.
234
235 On POSIX systems this method sends :py:data:`signal.SIGTERM` to the
236 child process.
237
238 On Windows the Win32 API function :c:func:`TerminateProcess` is
239 called to stop the child process.
Victor Stinner08444382014-02-02 22:43:39 +0100240
Victor Stinner39892052014-10-14 00:52:07 +0200241 .. method:: kill()
Victor Stinner08444382014-02-02 22:43:39 +0100242
Yury Selivanov512d7102018-09-17 19:35:30 -0400243 Kill the child.
244
245 On POSIX systems this method sends :py:data:`SIGKILL` to the child
246 process.
247
248 On Windows this method is an alias for :meth:`terminate`.
Victor Stinner08444382014-02-02 22:43:39 +0100249
Victor Stinner39892052014-10-14 00:52:07 +0200250 .. attribute:: stdin
251
Yury Selivanov512d7102018-09-17 19:35:30 -0400252 Standard input stream (:class:`StreamWriter`) or ``None``
253 if the process was created with ``stdin=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200254
255 .. attribute:: stdout
256
Yury Selivanov512d7102018-09-17 19:35:30 -0400257 Standard output stream (:class:`StreamReader`) or ``None``
258 if the process was created with ``stdout=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200259
260 .. attribute:: stderr
261
Yury Selivanov512d7102018-09-17 19:35:30 -0400262 Standard error stream (:class:`StreamReader`) or ``None``
263 if the process was created with ``stderr=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200264
265 .. warning::
266
Yury Selivanov512d7102018-09-17 19:35:30 -0400267 Use the :meth:`communicate` method rather than
268 :attr:`process.stdin.write() <stdin>`,
269 :attr:`await process.stdout.read() <stdout>` or
270 :attr:`await process.stderr.read <stderr>`.
271 This avoids deadlocks due to streams pausing reading or writing
272 and blocking the child process.
Victor Stinner39892052014-10-14 00:52:07 +0200273
274 .. attribute:: pid
275
Yury Selivanov512d7102018-09-17 19:35:30 -0400276 Process identification number (PID).
Victor Stinner39892052014-10-14 00:52:07 +0200277
278 Note that for processes created by the :func:`create_subprocess_shell`
Yury Selivanov512d7102018-09-17 19:35:30 -0400279 function, this attribute is the PID of the spawned shell.
Victor Stinner39892052014-10-14 00:52:07 +0200280
281 .. attribute:: returncode
282
Yury Selivanov512d7102018-09-17 19:35:30 -0400283 Return code of the process when it exits.
Victor Stinner39892052014-10-14 00:52:07 +0200284
Yury Selivanov512d7102018-09-17 19:35:30 -0400285 A ``None`` value indicates that the process has not terminated yet.
286
287 A negative value ``-N`` indicates that the child was terminated
288 by signal ``N`` (POSIX only).
Victor Stinner7bdf7862014-03-16 21:29:31 +0100289
Victor Stinnere48d4db2014-02-03 23:26:28 +0100290
Victor Stinner399c59d2015-01-09 01:32:02 +0100291.. _asyncio-subprocess-threads:
292
Yury Selivanov512d7102018-09-17 19:35:30 -0400293Subprocess and Threads
Victor Stinner5492d352015-09-02 15:39:01 +0200294----------------------
Victor Stinner399c59d2015-01-09 01:32:02 +0100295
Yury Selivanov512d7102018-09-17 19:35:30 -0400296Standard asyncio event loop supports running subprocesses from
297different threads, but there are limitations:
Victor Stinner399c59d2015-01-09 01:32:02 +0100298
Yury Selivanov512d7102018-09-17 19:35:30 -0400299* An event loop must run in the main thread.
Victor Stinner399c59d2015-01-09 01:32:02 +0100300
Yury Selivanov512d7102018-09-17 19:35:30 -0400301* The child watcher must be instantiated in the main thread
302 before executing subprocesses from other threads. Call the
303 :func:`get_child_watcher` function in the main thread to instantiate
304 the child watcher.
305
306Note that alternative event loop implementations might not share
307the above limitations; please refer to their documentation.
Victor Stinner83704962015-02-25 14:24:15 +0100308
Victor Stinner399c59d2015-01-09 01:32:02 +0100309.. seealso::
310
311 The :ref:`Concurrency and multithreading in asyncio
312 <asyncio-multithreading>` section.
313
314
Yury Selivanov512d7102018-09-17 19:35:30 -0400315Examples
316--------
Victor Stinnere48d4db2014-02-03 23:26:28 +0100317
Yury Selivanov512d7102018-09-17 19:35:30 -0400318An example using the :class:`~asyncio.subprocess.Process` class to
319control a subprocess and the :class:`StreamReader` class to read from
320its standard output.
Victor Stinner39892052014-10-14 00:52:07 +0200321
Yury Selivanov512d7102018-09-17 19:35:30 -0400322.. _asyncio_example_create_subprocess_exec:
Victor Stinnere48d4db2014-02-03 23:26:28 +0100323
Yury Selivanov512d7102018-09-17 19:35:30 -0400324The subprocess is created by the :func:`create_subprocess_exec`
Victor Stinner39892052014-10-14 00:52:07 +0200325function::
326
Yury Selivanov512d7102018-09-17 19:35:30 -0400327 import asyncio
Victor Stinner39892052014-10-14 00:52:07 +0200328 import sys
329
Miss Islington (bot)fac49762018-08-07 13:33:31 -0700330 async def get_date():
Victor Stinner39892052014-10-14 00:52:07 +0200331 code = 'import datetime; print(datetime.datetime.now())'
332
Yury Selivanov512d7102018-09-17 19:35:30 -0400333 # Create the subprocess; redirect the standard output
334 # into a pipe.
Andrew Svetlov88743422017-12-11 17:35:49 +0200335 proc = await asyncio.create_subprocess_exec(
336 sys.executable, '-c', code,
337 stdout=asyncio.subprocess.PIPE)
Victor Stinner39892052014-10-14 00:52:07 +0200338
Yury Selivanov512d7102018-09-17 19:35:30 -0400339 # Read one line of output.
Andrew Svetlov88743422017-12-11 17:35:49 +0200340 data = await proc.stdout.readline()
Victor Stinner39892052014-10-14 00:52:07 +0200341 line = data.decode('ascii').rstrip()
342
Yury Selivanov512d7102018-09-17 19:35:30 -0400343 # Wait for the subprocess exit.
Andrew Svetlov88743422017-12-11 17:35:49 +0200344 await proc.wait()
Victor Stinner39892052014-10-14 00:52:07 +0200345 return line
346
347 if sys.platform == "win32":
Yury Selivanov512d7102018-09-17 19:35:30 -0400348 asyncio.set_event_loop_policy(
349 asyncio.WindowsProactorEventLoopPolicy())
Victor Stinner39892052014-10-14 00:52:07 +0200350
Yury Selivanov512d7102018-09-17 19:35:30 -0400351 date = asyncio.run(get_date())
352 print(f"Current date: {date}")
353
354
355See also the :ref:`same example <asyncio_example_subprocess_proto>`
356written using low-level APIs.