blob: b0330349dfb651927917879b9369a3299fd0f5ad [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
sth4a0ac422020-05-26 06:08:40 +020098 .. important::
Victor Stinner984600f2014-03-25 09:40:26 +010099
sth4a0ac422020-05-26 06:08:40 +0200100 It is the application's responsibility to ensure that all whitespace and
101 special characters are quoted appropriately to avoid `shell injection
102 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
103 vulnerabilities. The :func:`shlex.quote` function can be used to properly
104 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
Zackery Spytz4dfb1902020-10-19 16:08:34 -0600113 Subprocesses are available for Windows if a :class:`ProactorEventLoop` is
114 used. See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700115 for details.
Victor Stinner984600f2014-03-25 09:40:26 +0100116
Victor Stinner08444382014-02-02 22:43:39 +0100117.. seealso::
118
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400119 asyncio also has the following *low-level* APIs to work with subprocesses:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700120 :meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`,
121 :meth:`loop.connect_read_pipe`, :meth:`loop.connect_write_pipe`,
122 as well as the :ref:`Subprocess Transports <asyncio-subprocess-transports>`
123 and :ref:`Subprocess Protocols <asyncio-subprocess-protocols>`.
Victor Stinner08444382014-02-02 22:43:39 +0100124
125
126Constants
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700127=========
Victor Stinner08444382014-02-02 22:43:39 +0100128
129.. data:: asyncio.subprocess.PIPE
130
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700131 Can be passed to the *stdin*, *stdout* or *stderr* parameters.
132
133 If *PIPE* is passed to *stdin* argument, the
134 :attr:`Process.stdin <asyncio.subprocess.Process.stdin>` attribute
135 will point to a :class:`StreamWriter` instance.
136
137 If *PIPE* is passed to *stdout* or *stderr* arguments, the
138 :attr:`Process.stdout <asyncio.subprocess.Process.stdout>` and
139 :attr:`Process.stderr <asyncio.subprocess.Process.stderr>`
140 attributes will point to :class:`StreamReader` instances.
Victor Stinner08444382014-02-02 22:43:39 +0100141
142.. data:: asyncio.subprocess.STDOUT
143
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400144 Special value that can be used as the *stderr* argument and indicates
145 that standard error should be redirected into standard output.
Victor Stinner08444382014-02-02 22:43:39 +0100146
147.. data:: asyncio.subprocess.DEVNULL
148
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400149 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
150 to process creation functions. It indicates that the special file
151 :data:`os.devnull` will be used for the corresponding subprocess stream.
Victor Stinner08444382014-02-02 22:43:39 +0100152
153
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700154Interacting with Subprocesses
155=============================
156
157Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400158functions return instances of the *Process* class. *Process* is a high-level
159wrapper that allows communicating with subprocesses and watching for
160their completion.
Victor Stinner08444382014-02-02 22:43:39 +0100161
162.. class:: asyncio.subprocess.Process
163
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700164 An object that wraps OS processes created by the
165 :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
166 functions.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100167
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700168 This class is designed to have a similar API to the
169 :class:`subprocess.Popen` class, but there are some
170 notable differences:
Victor Stinnerb79eb052014-02-03 23:08:14 +0100171
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700172 * unlike Popen, Process instances do not have an equivalent to
173 the :meth:`~subprocess.Popen.poll` method;
Victor Stinnerb79eb052014-02-03 23:08:14 +0100174
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700175 * the :meth:`~asyncio.subprocess.Process.communicate` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400176 :meth:`~asyncio.subprocess.Process.wait` methods don't have a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700177 *timeout* parameter: use the :func:`wait_for` function;
178
179 * the :meth:`Process.wait() <asyncio.subprocess.Process.wait>` method
180 is asynchronous, whereas :meth:`subprocess.Popen.wait` method
181 is implemented as a blocking busy loop;
182
183 * the *universal_newlines* parameter is not supported.
184
185 This class is :ref:`not thread safe <asyncio-multithreading>`.
186
187 See also the :ref:`Subprocess and Threads <asyncio-subprocess-threads>`
188 section.
Victor Stinner83704962015-02-25 14:24:15 +0100189
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100190 .. coroutinemethod:: wait()
Victor Stinnerb79eb052014-02-03 23:08:14 +0100191
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400192 Wait for the child process to terminate.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100193
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700194 Set and return the :attr:`returncode` attribute.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100195
Victor Stinner39892052014-10-14 00:52:07 +0200196 .. note::
Victor Stinner08444382014-02-02 22:43:39 +0100197
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700198 This method can deadlock when using ``stdout=PIPE`` or
199 ``stderr=PIPE`` and the child process generates so much output
200 that it blocks waiting for the OS pipe buffer to accept
201 more data. Use the :meth:`communicate` method when using pipes
202 to avoid this condition.
Victor Stinner08444382014-02-02 22:43:39 +0100203
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100204 .. coroutinemethod:: communicate(input=None)
Victor Stinner08444382014-02-02 22:43:39 +0100205
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700206 Interact with process:
Victor Stinner08444382014-02-02 22:43:39 +0100207
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700208 1. send data to *stdin* (if *input* is not ``None``);
209 2. read data from *stdout* and *stderr*, until EOF is reached;
210 3. wait for process to terminate.
Victor Stinner39892052014-10-14 00:52:07 +0200211
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700212 The optional *input* argument is the data (:class:`bytes` object)
213 that will be sent to the child process.
Victor Stinnercc996b52014-07-17 12:25:27 +0200214
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700215 Return a tuple ``(stdout_data, stderr_data)``.
Victor Stinner08444382014-02-02 22:43:39 +0100216
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700217 If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError`
218 exception is raised when writing *input* into *stdin*, the
219 exception is ignored. This condition occurs when the process
220 exits before all data are written into *stdin*.
Victor Stinner39892052014-10-14 00:52:07 +0200221
Carol Willing4e824e92018-09-13 18:28:19 -0700222 If it is desired to send data to the process' *stdin*,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700223 the process needs to be created with ``stdin=PIPE``. Similarly,
224 to get anything other than ``None`` in the result tuple, the
225 process has to be created with ``stdout=PIPE`` and/or
226 ``stderr=PIPE`` arguments.
Victor Stinner08444382014-02-02 22:43:39 +0100227
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700228 Note, that the data read is buffered in memory, so do not use
229 this method if the data size is large or unlimited.
Victor Stinnercc996b52014-07-17 12:25:27 +0200230
Brian Curtina1afeec2014-02-08 18:36:14 -0600231 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100232
233 Sends the signal *signal* to the child process.
234
235 .. note::
236
237 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
238 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
239 started with a *creationflags* parameter which includes
240 ``CREATE_NEW_PROCESS_GROUP``.
241
242 .. method:: terminate()
243
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400244 Stop the child process.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700245
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400246 On POSIX systems this method sends :py:data:`signal.SIGTERM` to the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700247 child process.
248
249 On Windows the Win32 API function :c:func:`TerminateProcess` is
250 called to stop the child process.
Victor Stinner08444382014-02-02 22:43:39 +0100251
Victor Stinner39892052014-10-14 00:52:07 +0200252 .. method:: kill()
Victor Stinner08444382014-02-02 22:43:39 +0100253
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700254 Kill the child.
255
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400256 On POSIX systems this method sends :py:data:`SIGKILL` to the child
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700257 process.
258
259 On Windows this method is an alias for :meth:`terminate`.
Victor Stinner08444382014-02-02 22:43:39 +0100260
Victor Stinner39892052014-10-14 00:52:07 +0200261 .. attribute:: stdin
262
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700263 Standard input stream (:class:`StreamWriter`) or ``None``
264 if the process was created with ``stdin=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200265
266 .. attribute:: stdout
267
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700268 Standard output stream (:class:`StreamReader`) or ``None``
269 if the process was created with ``stdout=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200270
271 .. attribute:: stderr
272
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700273 Standard error stream (:class:`StreamReader`) or ``None``
274 if the process was created with ``stderr=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200275
276 .. warning::
277
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700278 Use the :meth:`communicate` method rather than
279 :attr:`process.stdin.write() <stdin>`,
280 :attr:`await process.stdout.read() <stdout>` or
Carol Willing4e824e92018-09-13 18:28:19 -0700281 :attr:`await process.stderr.read <stderr>`.
282 This avoids deadlocks due to streams pausing reading or writing
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700283 and blocking the child process.
Victor Stinner39892052014-10-14 00:52:07 +0200284
285 .. attribute:: pid
286
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700287 Process identification number (PID).
Victor Stinner39892052014-10-14 00:52:07 +0200288
289 Note that for processes created by the :func:`create_subprocess_shell`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700290 function, this attribute is the PID of the spawned shell.
Victor Stinner39892052014-10-14 00:52:07 +0200291
292 .. attribute:: returncode
293
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700294 Return code of the process when it exits.
Victor Stinner39892052014-10-14 00:52:07 +0200295
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700296 A ``None`` value indicates that the process has not terminated yet.
297
298 A negative value ``-N`` indicates that the child was terminated
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400299 by signal ``N`` (POSIX only).
Victor Stinner7bdf7862014-03-16 21:29:31 +0100300
Victor Stinnere48d4db2014-02-03 23:26:28 +0100301
Victor Stinner399c59d2015-01-09 01:32:02 +0100302.. _asyncio-subprocess-threads:
303
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700304Subprocess and Threads
Victor Stinner5492d352015-09-02 15:39:01 +0200305----------------------
Victor Stinner399c59d2015-01-09 01:32:02 +0100306
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300307Standard asyncio event loop supports running subprocesses from different threads by
308default.
Victor Stinner399c59d2015-01-09 01:32:02 +0100309
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300310On Windows subprocesses are provided by :class:`ProactorEventLoop` only (default),
311:class:`SelectorEventLoop` has no subprocess support.
Victor Stinner399c59d2015-01-09 01:32:02 +0100312
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300313On UNIX *child watchers* are used for subprocess finish waiting, see
314:ref:`asyncio-watchers` for more info.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700315
Andrew Svetlov0d671c02019-06-30 12:54:59 +0300316
317.. versionchanged:: 3.8
318
319 UNIX switched to use :class:`ThreadedChildWatcher` for spawning subprocesses from
320 different threads without any limitation.
321
322 Spawning a subprocess with *inactive* current child watcher raises
323 :exc:`RuntimeError`.
324
325Note that alternative event loop implementations might have own limitations;
326please refer to their documentation.
Victor Stinner83704962015-02-25 14:24:15 +0100327
Victor Stinner399c59d2015-01-09 01:32:02 +0100328.. seealso::
329
330 The :ref:`Concurrency and multithreading in asyncio
331 <asyncio-multithreading>` section.
332
333
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700334Examples
335--------
Victor Stinnere48d4db2014-02-03 23:26:28 +0100336
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700337An example using the :class:`~asyncio.subprocess.Process` class to
338control a subprocess and the :class:`StreamReader` class to read from
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400339its standard output.
Victor Stinner39892052014-10-14 00:52:07 +0200340
Yury Selivanov394374e2018-09-17 15:35:24 -0400341.. _asyncio_example_create_subprocess_exec:
342
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700343The subprocess is created by the :func:`create_subprocess_exec`
Victor Stinner39892052014-10-14 00:52:07 +0200344function::
345
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700346 import asyncio
Victor Stinner39892052014-10-14 00:52:07 +0200347 import sys
348
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400349 async def get_date():
Victor Stinner39892052014-10-14 00:52:07 +0200350 code = 'import datetime; print(datetime.datetime.now())'
351
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700352 # Create the subprocess; redirect the standard output
353 # into a pipe.
Andrew Svetlov88743422017-12-11 17:35:49 +0200354 proc = await asyncio.create_subprocess_exec(
355 sys.executable, '-c', code,
356 stdout=asyncio.subprocess.PIPE)
Victor Stinner39892052014-10-14 00:52:07 +0200357
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700358 # Read one line of output.
Andrew Svetlov88743422017-12-11 17:35:49 +0200359 data = await proc.stdout.readline()
Victor Stinner39892052014-10-14 00:52:07 +0200360 line = data.decode('ascii').rstrip()
361
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700362 # Wait for the subprocess exit.
Andrew Svetlov88743422017-12-11 17:35:49 +0200363 await proc.wait()
Victor Stinner39892052014-10-14 00:52:07 +0200364 return line
365
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700366 date = asyncio.run(get_date())
367 print(f"Current date: {date}")
368
369
Yury Selivanov394374e2018-09-17 15:35:24 -0400370See also the :ref:`same example <asyncio_example_subprocess_proto>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700371written using low-level APIs.