blob: 92c081b70bfccffe96b42208ebba7ba762640eb9 [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 Selivanov7c7605f2018-09-11 09:54:40 -070012Here's an example of how asyncio can run a shell command and
13communicate its result back::
Victor Stinner984600f2014-03-25 09:40:26 +010014
Yury Selivanov7c7605f2018-09-11 09:54:40 -070015 import asyncio
Victor Stinner984600f2014-03-25 09:40:26 +010016
Yury Selivanov7c7605f2018-09-11 09:54:40 -070017 async def run(cmd):
18 proc = await asyncio.create_subprocess_shell(
19 cmd,
20 stdout=asyncio.subprocess.PIPE,
21 stderr=asyncio.subprocess.PIPE)
Victor Stinneraea82292014-07-08 23:42:38 +020022
Yury Selivanov7c7605f2018-09-11 09:54:40 -070023 stdout, stderr = await proc.communicate()
Victor Stinner984600f2014-03-25 09:40:26 +010024
Yury Selivanov7c7605f2018-09-11 09:54:40 -070025 print(f'[{cmd!r} exited with {proc.returncode}]')
26 if stdout:
27 print(f'[stdout]\n{stdout.decode()}')
28 if stderr:
29 print(f'[stderr]\n{stderr.decode()}')
Victor Stinner778015b2014-07-11 12:13:39 +020030
Yury Selivanov7c7605f2018-09-11 09:54:40 -070031 asyncio.run(run('ls /zzz'))
32
33will print::
34
35 ['ls /zzz' exited with 1]
36 [stderr]
37 ls: /zzz: No such file or directory
38
39Because all asyncio subprocess functions are asynchronous and asyncio
40provides many tools to work with such functions, it is easy to execute
41and monitor multiple subprocesses in parallel. It is indeed trivial
42to modify the above example to run a few commands at once::
43
44 async def main():
45 await asyncio.gather(
46 run('ls /zzz'),
47 run('sleep 1; echo "hello"'))
48
49 asyncio.run(main())
50
51See also the `Examples`_ subsection.
Victor Stinner778015b2014-07-11 12:13:39 +020052
Victor Stinner984600f2014-03-25 09:40:26 +010053
Yury Selivanov7c7605f2018-09-11 09:54:40 -070054Creating Subprocesses
55=====================
Victor Stinner08444382014-02-02 22:43:39 +010056
Yury Selivanov7c7605f2018-09-11 09:54:40 -070057.. coroutinefunction:: create_subprocess_exec(\*args, stdin=None, \
58 stdout=None, stderr=None, loop=None, \
59 limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010060
Victor Stinner39892052014-10-14 00:52:07 +020061 Create a subprocess.
Victor Stinner08444382014-02-02 22:43:39 +010062
Yury Selivanov7c7605f2018-09-11 09:54:40 -070063 The *limit* argument sets the buffer limit for :class:`StreamReader`
64 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
Carol Willing4e824e92018-09-13 18:28:19 -070065 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments).
Victor Stinner39892052014-10-14 00:52:07 +020066
67 Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner984600f2014-03-25 09:40:26 +010068
Yury Selivanov7c7605f2018-09-11 09:54:40 -070069 See the documentation of :meth:`loop.subprocess_exec` for other
70 parameters.
Victor Stinner08444382014-02-02 22:43:39 +010071
Yury Selivanov7c7605f2018-09-11 09:54:40 -070072.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \
73 stdout=None, stderr=None, loop=None, \
74 limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010075
Victor Stinner39892052014-10-14 00:52:07 +020076 Run the shell command *cmd*.
Victor Stinner08444382014-02-02 22:43:39 +010077
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078 The *limit* argument sets the buffer limit for :class:`StreamReader`
79 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
Carol Willing4e824e92018-09-13 18:28:19 -070080 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr* arguments).
Victor Stinner39892052014-10-14 00:52:07 +020081
82 Return a :class:`~asyncio.subprocess.Process` instance.
83
Yury Selivanov7c7605f2018-09-11 09:54:40 -070084 See the documentation of :meth:`loop.subprocess_shell` for other
85 parameters.
Victor Stinner984600f2014-03-25 09:40:26 +010086
Carol Willing4e824e92018-09-13 18:28:19 -070087.. important::
Victor Stinner984600f2014-03-25 09:40:26 +010088
Victor Stinner39892052014-10-14 00:52:07 +020089 It is the application's responsibility to ensure that all whitespace and
90 metacharacters are quoted appropriately to avoid `shell injection
Georg Brandl5d941342016-02-26 19:37:12 +010091 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
Victor Stinner39892052014-10-14 00:52:07 +020092 vulnerabilities. The :func:`shlex.quote` function can be used to properly
93 escape whitespace and shell metacharacters in strings that are going to be
94 used to construct shell commands.
Victor Stinner984600f2014-03-25 09:40:26 +010095
Yury Selivanov7c7605f2018-09-11 09:54:40 -070096.. note::
97
98 The default event loop that asyncio is pre-configured
Carol Willing4e824e92018-09-13 18:28:19 -070099 to use on **Windows** does not support subprocesses. Subprocesses are
100 available for Windows if the :class:`ProactorEventLoop` is used.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700101 See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
102 for details.
Victor Stinner984600f2014-03-25 09:40:26 +0100103
Victor Stinner08444382014-02-02 22:43:39 +0100104.. seealso::
105
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700106 asyncio has also *low-level* APIs to work with subprocesses:
107 :meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`,
108 :meth:`loop.connect_read_pipe`, :meth:`loop.connect_write_pipe`,
109 as well as the :ref:`Subprocess Transports <asyncio-subprocess-transports>`
110 and :ref:`Subprocess Protocols <asyncio-subprocess-protocols>`.
Victor Stinner08444382014-02-02 22:43:39 +0100111
112
113Constants
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700114=========
Victor Stinner08444382014-02-02 22:43:39 +0100115
116.. data:: asyncio.subprocess.PIPE
117
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700118 Can be passed to the *stdin*, *stdout* or *stderr* parameters.
119
120 If *PIPE* is passed to *stdin* argument, the
121 :attr:`Process.stdin <asyncio.subprocess.Process.stdin>` attribute
122 will point to a :class:`StreamWriter` instance.
123
124 If *PIPE* is passed to *stdout* or *stderr* arguments, the
125 :attr:`Process.stdout <asyncio.subprocess.Process.stdout>` and
126 :attr:`Process.stderr <asyncio.subprocess.Process.stderr>`
127 attributes will point to :class:`StreamReader` instances.
Victor Stinner08444382014-02-02 22:43:39 +0100128
129.. data:: asyncio.subprocess.STDOUT
130
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700131 Can be passed to the *stderr* parameter to redirect process'
132 *stderr* to *stdout*.
Victor Stinner08444382014-02-02 22:43:39 +0100133
134.. data:: asyncio.subprocess.DEVNULL
135
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700136 Can be passed as the *stdin*, *stdout* or *stderr* parameters
137 to redirect the corresponding subprocess' IO to :data:`os.devnull`.
Victor Stinner08444382014-02-02 22:43:39 +0100138
139
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700140Interacting with Subprocesses
141=============================
142
143Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
144functions return instances of the *Process* class. It is a high-level
145wrapper that allows to watch for subprocesses completion and
146communicate with them.
Victor Stinner08444382014-02-02 22:43:39 +0100147
148.. class:: asyncio.subprocess.Process
149
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700150 An object that wraps OS processes created by the
151 :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
152 functions.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100153
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700154 This class is designed to have a similar API to the
155 :class:`subprocess.Popen` class, but there are some
156 notable differences:
Victor Stinnerb79eb052014-02-03 23:08:14 +0100157
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700158 * unlike Popen, Process instances do not have an equivalent to
159 the :meth:`~subprocess.Popen.poll` method;
Victor Stinnerb79eb052014-02-03 23:08:14 +0100160
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700161 * the :meth:`~asyncio.subprocess.Process.communicate` and
162 :meth:`~asyncio.subprocess.Process.wait` methods don't take a
163 *timeout* parameter: use the :func:`wait_for` function;
164
165 * the :meth:`Process.wait() <asyncio.subprocess.Process.wait>` method
166 is asynchronous, whereas :meth:`subprocess.Popen.wait` method
167 is implemented as a blocking busy loop;
168
169 * the *universal_newlines* parameter is not supported.
170
171 This class is :ref:`not thread safe <asyncio-multithreading>`.
172
173 See also the :ref:`Subprocess and Threads <asyncio-subprocess-threads>`
174 section.
Victor Stinner83704962015-02-25 14:24:15 +0100175
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100176 .. coroutinemethod:: wait()
Victor Stinnerb79eb052014-02-03 23:08:14 +0100177
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700178 Wait for child process to terminate.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100179
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700180 Set and return the :attr:`returncode` attribute.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100181
Victor Stinner39892052014-10-14 00:52:07 +0200182 .. note::
Victor Stinner08444382014-02-02 22:43:39 +0100183
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700184 This method can deadlock when using ``stdout=PIPE`` or
185 ``stderr=PIPE`` and the child process generates so much output
186 that it blocks waiting for the OS pipe buffer to accept
187 more data. Use the :meth:`communicate` method when using pipes
188 to avoid this condition.
Victor Stinner08444382014-02-02 22:43:39 +0100189
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100190 .. coroutinemethod:: communicate(input=None)
Victor Stinner08444382014-02-02 22:43:39 +0100191
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700192 Interact with process:
Victor Stinner08444382014-02-02 22:43:39 +0100193
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700194 1. send data to *stdin* (if *input* is not ``None``);
195 2. read data from *stdout* and *stderr*, until EOF is reached;
196 3. wait for process to terminate.
Victor Stinner39892052014-10-14 00:52:07 +0200197
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700198 The optional *input* argument is the data (:class:`bytes` object)
199 that will be sent to the child process.
Victor Stinnercc996b52014-07-17 12:25:27 +0200200
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700201 Return a tuple ``(stdout_data, stderr_data)``.
Victor Stinner08444382014-02-02 22:43:39 +0100202
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700203 If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError`
204 exception is raised when writing *input* into *stdin*, the
205 exception is ignored. This condition occurs when the process
206 exits before all data are written into *stdin*.
Victor Stinner39892052014-10-14 00:52:07 +0200207
Carol Willing4e824e92018-09-13 18:28:19 -0700208 If it is desired to send data to the process' *stdin*,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700209 the process needs to be created with ``stdin=PIPE``. Similarly,
210 to get anything other than ``None`` in the result tuple, the
211 process has to be created with ``stdout=PIPE`` and/or
212 ``stderr=PIPE`` arguments.
Victor Stinner08444382014-02-02 22:43:39 +0100213
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700214 Note, that the data read is buffered in memory, so do not use
215 this method if the data size is large or unlimited.
Victor Stinnercc996b52014-07-17 12:25:27 +0200216
Brian Curtina1afeec2014-02-08 18:36:14 -0600217 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100218
219 Sends the signal *signal* to the child process.
220
221 .. note::
222
223 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
224 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
225 started with a *creationflags* parameter which includes
226 ``CREATE_NEW_PROCESS_GROUP``.
227
228 .. method:: terminate()
229
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700230 Stop the child.
231
232 On Posix OSs the method sends :py:data:`signal.SIGTERM` to the
233 child process.
234
235 On Windows the Win32 API function :c:func:`TerminateProcess` is
236 called to stop the child process.
Victor Stinner08444382014-02-02 22:43:39 +0100237
Victor Stinner39892052014-10-14 00:52:07 +0200238 .. method:: kill()
Victor Stinner08444382014-02-02 22:43:39 +0100239
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700240 Kill the child.
241
242 On Posix OSs the function sends :py:data:`SIGKILL` to the child
243 process.
244
245 On Windows this method is an alias for :meth:`terminate`.
Victor Stinner08444382014-02-02 22:43:39 +0100246
Victor Stinner39892052014-10-14 00:52:07 +0200247 .. attribute:: stdin
248
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700249 Standard input stream (:class:`StreamWriter`) or ``None``
250 if the process was created with ``stdin=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200251
252 .. attribute:: stdout
253
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700254 Standard output stream (:class:`StreamReader`) or ``None``
255 if the process was created with ``stdout=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200256
257 .. attribute:: stderr
258
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700259 Standard error stream (:class:`StreamReader`) or ``None``
260 if the process was created with ``stderr=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200261
262 .. warning::
263
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700264 Use the :meth:`communicate` method rather than
265 :attr:`process.stdin.write() <stdin>`,
266 :attr:`await process.stdout.read() <stdout>` or
Carol Willing4e824e92018-09-13 18:28:19 -0700267 :attr:`await process.stderr.read <stderr>`.
268 This avoids deadlocks due to streams pausing reading or writing
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700269 and blocking the child process.
Victor Stinner39892052014-10-14 00:52:07 +0200270
271 .. attribute:: pid
272
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700273 Process identification number (PID).
Victor Stinner39892052014-10-14 00:52:07 +0200274
275 Note that for processes created by the :func:`create_subprocess_shell`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700276 function, this attribute is the PID of the spawned shell.
Victor Stinner39892052014-10-14 00:52:07 +0200277
278 .. attribute:: returncode
279
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700280 Return code of the process when it exits.
Victor Stinner39892052014-10-14 00:52:07 +0200281
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700282 A ``None`` value indicates that the process has not terminated yet.
283
284 A negative value ``-N`` indicates that the child was terminated
285 by signal ``N`` (Unix only).
Victor Stinner7bdf7862014-03-16 21:29:31 +0100286
Victor Stinnere48d4db2014-02-03 23:26:28 +0100287
Victor Stinner399c59d2015-01-09 01:32:02 +0100288.. _asyncio-subprocess-threads:
289
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700290Subprocess and Threads
Victor Stinner5492d352015-09-02 15:39:01 +0200291----------------------
Victor Stinner399c59d2015-01-09 01:32:02 +0100292
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700293asyncio built-in event loops support running subprocesses from
294different threads, but there are the following limitations:
Victor Stinner399c59d2015-01-09 01:32:02 +0100295
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700296* An event loop must run in the main thread.
Victor Stinner399c59d2015-01-09 01:32:02 +0100297
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700298* The child watcher must be instantiated in the main thread,
299 before executing subprocesses from other threads. Call the
300 :func:`get_child_watcher` function in the main thread to instantiate
301 the child watcher.
302
303Note, that alternative event loop implementations might not share
304the above limitations; please refer to their documentation.
Victor Stinner83704962015-02-25 14:24:15 +0100305
Victor Stinner399c59d2015-01-09 01:32:02 +0100306.. seealso::
307
308 The :ref:`Concurrency and multithreading in asyncio
309 <asyncio-multithreading>` section.
310
311
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700312Examples
313--------
Victor Stinnere48d4db2014-02-03 23:26:28 +0100314
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700315An example using the :class:`~asyncio.subprocess.Process` class to
316control a subprocess and the :class:`StreamReader` class to read from
317the *stdout*.
Victor Stinner39892052014-10-14 00:52:07 +0200318
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700319The subprocess is created by the :func:`create_subprocess_exec`
Victor Stinner39892052014-10-14 00:52:07 +0200320function::
321
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700322 import asyncio
Victor Stinner39892052014-10-14 00:52:07 +0200323 import sys
324
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400325 async def get_date():
Victor Stinner39892052014-10-14 00:52:07 +0200326 code = 'import datetime; print(datetime.datetime.now())'
327
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700328 # Create the subprocess; redirect the standard output
329 # into a pipe.
Andrew Svetlov88743422017-12-11 17:35:49 +0200330 proc = await asyncio.create_subprocess_exec(
331 sys.executable, '-c', code,
332 stdout=asyncio.subprocess.PIPE)
Victor Stinner39892052014-10-14 00:52:07 +0200333
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700334 # Read one line of output.
Andrew Svetlov88743422017-12-11 17:35:49 +0200335 data = await proc.stdout.readline()
Victor Stinner39892052014-10-14 00:52:07 +0200336 line = data.decode('ascii').rstrip()
337
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700338 # Wait for the subprocess exit.
Andrew Svetlov88743422017-12-11 17:35:49 +0200339 await proc.wait()
Victor Stinner39892052014-10-14 00:52:07 +0200340 return line
341
342 if sys.platform == "win32":
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700343 asyncio.set_event_loop_policy(
344 asyncio.WindowsProactorEventLoopPolicy())
Victor Stinner39892052014-10-14 00:52:07 +0200345
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700346 date = asyncio.run(get_date())
347 print(f"Current date: {date}")
348
349
350See also the :ref:`same example <asyncio-subprocess-proto-example>`
351written using low-level APIs.