blob: b05c236bb0c8689d54818ddc78ce7e862bb4e177 [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`
65 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr*
66 arguments).
Victor Stinner39892052014-10-14 00:52:07 +020067
68 Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner984600f2014-03-25 09:40:26 +010069
Yury Selivanov7c7605f2018-09-11 09:54:40 -070070 See the documentation of :meth:`loop.subprocess_exec` for other
71 parameters.
Victor Stinner08444382014-02-02 22:43:39 +010072
Yury Selivanov7c7605f2018-09-11 09:54:40 -070073.. coroutinefunction:: create_subprocess_shell(cmd, stdin=None, \
74 stdout=None, stderr=None, loop=None, \
75 limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010076
Victor Stinner39892052014-10-14 00:52:07 +020077 Run the shell command *cmd*.
Victor Stinner08444382014-02-02 22:43:39 +010078
Yury Selivanov7c7605f2018-09-11 09:54:40 -070079 The *limit* argument sets the buffer limit for :class:`StreamReader`
80 wrappers for :attr:`Process.stdout` and :attr:`Process.stderr`
81 (if :attr:`subprocess.PIPE` is passed to *stdout* and *stderr*
82 arguments).
Victor Stinner39892052014-10-14 00:52:07 +020083
84 Return a :class:`~asyncio.subprocess.Process` instance.
85
Yury Selivanov7c7605f2018-09-11 09:54:40 -070086 See the documentation of :meth:`loop.subprocess_shell` for other
87 parameters.
Victor Stinner984600f2014-03-25 09:40:26 +010088
Yury Selivanov7c7605f2018-09-11 09:54:40 -070089.. note::
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
92 metacharacters 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
95 escape whitespace and shell metacharacters in strings that are going to be
96 used to construct shell commands.
Victor Stinner984600f2014-03-25 09:40:26 +010097
Yury Selivanov7c7605f2018-09-11 09:54:40 -070098.. note::
99
100 The default event loop that asyncio is pre-configured
101 to use on **Windows** does not support subprocesses.
102 See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
103 for details.
Victor Stinner984600f2014-03-25 09:40:26 +0100104
Victor Stinner08444382014-02-02 22:43:39 +0100105.. seealso::
106
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700107 asyncio has also *low-level* APIs to work with subprocesses:
108 :meth:`loop.subprocess_exec`, :meth:`loop.subprocess_shell`,
109 :meth:`loop.connect_read_pipe`, :meth:`loop.connect_write_pipe`,
110 as well as the :ref:`Subprocess Transports <asyncio-subprocess-transports>`
111 and :ref:`Subprocess Protocols <asyncio-subprocess-protocols>`.
Victor Stinner08444382014-02-02 22:43:39 +0100112
113
114Constants
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700115=========
Victor Stinner08444382014-02-02 22:43:39 +0100116
117.. data:: asyncio.subprocess.PIPE
118
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700119 Can be passed to the *stdin*, *stdout* or *stderr* parameters.
120
121 If *PIPE* is passed to *stdin* argument, the
122 :attr:`Process.stdin <asyncio.subprocess.Process.stdin>` attribute
123 will point to a :class:`StreamWriter` instance.
124
125 If *PIPE* is passed to *stdout* or *stderr* arguments, the
126 :attr:`Process.stdout <asyncio.subprocess.Process.stdout>` and
127 :attr:`Process.stderr <asyncio.subprocess.Process.stderr>`
128 attributes will point to :class:`StreamReader` instances.
Victor Stinner08444382014-02-02 22:43:39 +0100129
130.. data:: asyncio.subprocess.STDOUT
131
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700132 Can be passed to the *stderr* parameter to redirect process'
133 *stderr* to *stdout*.
Victor Stinner08444382014-02-02 22:43:39 +0100134
135.. data:: asyncio.subprocess.DEVNULL
136
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700137 Can be passed as the *stdin*, *stdout* or *stderr* parameters
138 to redirect the corresponding subprocess' IO to :data:`os.devnull`.
Victor Stinner08444382014-02-02 22:43:39 +0100139
140
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700141Interacting with Subprocesses
142=============================
143
144Both :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
145functions return instances of the *Process* class. It is a high-level
146wrapper that allows to watch for subprocesses completion and
147communicate with them.
Victor Stinner08444382014-02-02 22:43:39 +0100148
149.. class:: asyncio.subprocess.Process
150
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700151 An object that wraps OS processes created by the
152 :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
153 functions.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100154
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700155 This class is designed to have a similar API to the
156 :class:`subprocess.Popen` class, but there are some
157 notable differences:
Victor Stinnerb79eb052014-02-03 23:08:14 +0100158
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700159 * unlike Popen, Process instances do not have an equivalent to
160 the :meth:`~subprocess.Popen.poll` method;
Victor Stinnerb79eb052014-02-03 23:08:14 +0100161
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700162 * the :meth:`~asyncio.subprocess.Process.communicate` and
163 :meth:`~asyncio.subprocess.Process.wait` methods don't take a
164 *timeout* parameter: use the :func:`wait_for` function;
165
166 * the :meth:`Process.wait() <asyncio.subprocess.Process.wait>` method
167 is asynchronous, whereas :meth:`subprocess.Popen.wait` method
168 is implemented as a blocking busy loop;
169
170 * the *universal_newlines* parameter is not supported.
171
172 This class is :ref:`not thread safe <asyncio-multithreading>`.
173
174 See also the :ref:`Subprocess and Threads <asyncio-subprocess-threads>`
175 section.
Victor Stinner83704962015-02-25 14:24:15 +0100176
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100177 .. coroutinemethod:: wait()
Victor Stinnerb79eb052014-02-03 23:08:14 +0100178
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700179 Wait for child process to terminate.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100180
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700181 Set and return the :attr:`returncode` attribute.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100182
Victor Stinner39892052014-10-14 00:52:07 +0200183 .. note::
Victor Stinner08444382014-02-02 22:43:39 +0100184
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700185 This method can deadlock when using ``stdout=PIPE`` or
186 ``stderr=PIPE`` and the child process generates so much output
187 that it blocks waiting for the OS pipe buffer to accept
188 more data. Use the :meth:`communicate` method when using pipes
189 to avoid this condition.
Victor Stinner08444382014-02-02 22:43:39 +0100190
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100191 .. coroutinemethod:: communicate(input=None)
Victor Stinner08444382014-02-02 22:43:39 +0100192
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700193 Interact with process:
Victor Stinner08444382014-02-02 22:43:39 +0100194
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700195 1. send data to *stdin* (if *input* is not ``None``);
196 2. read data from *stdout* and *stderr*, until EOF is reached;
197 3. wait for process to terminate.
Victor Stinner39892052014-10-14 00:52:07 +0200198
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700199 The optional *input* argument is the data (:class:`bytes` object)
200 that will be sent to the child process.
Victor Stinnercc996b52014-07-17 12:25:27 +0200201
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700202 Return a tuple ``(stdout_data, stderr_data)``.
Victor Stinner08444382014-02-02 22:43:39 +0100203
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700204 If either :exc:`BrokenPipeError` or :exc:`ConnectionResetError`
205 exception is raised when writing *input* into *stdin*, the
206 exception is ignored. This condition occurs when the process
207 exits before all data are written into *stdin*.
Victor Stinner39892052014-10-14 00:52:07 +0200208
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700209 If its desired to send data to the process' *stdin*,
210 the process needs to be created with ``stdin=PIPE``. Similarly,
211 to get anything other than ``None`` in the result tuple, the
212 process has to be created with ``stdout=PIPE`` and/or
213 ``stderr=PIPE`` arguments.
Victor Stinner08444382014-02-02 22:43:39 +0100214
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700215 Note, that the data read is buffered in memory, so do not use
216 this method if the data size is large or unlimited.
Victor Stinnercc996b52014-07-17 12:25:27 +0200217
Brian Curtina1afeec2014-02-08 18:36:14 -0600218 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100219
220 Sends the signal *signal* to the child process.
221
222 .. note::
223
224 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
225 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
226 started with a *creationflags* parameter which includes
227 ``CREATE_NEW_PROCESS_GROUP``.
228
229 .. method:: terminate()
230
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700231 Stop the child.
232
233 On Posix OSs the method sends :py:data:`signal.SIGTERM` to the
234 child process.
235
236 On Windows the Win32 API function :c:func:`TerminateProcess` is
237 called to stop the child process.
Victor Stinner08444382014-02-02 22:43:39 +0100238
Victor Stinner39892052014-10-14 00:52:07 +0200239 .. method:: kill()
Victor Stinner08444382014-02-02 22:43:39 +0100240
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700241 Kill the child.
242
243 On Posix OSs the function sends :py:data:`SIGKILL` to the child
244 process.
245
246 On Windows this method is an alias for :meth:`terminate`.
Victor Stinner08444382014-02-02 22:43:39 +0100247
Victor Stinner39892052014-10-14 00:52:07 +0200248 .. attribute:: stdin
249
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700250 Standard input stream (:class:`StreamWriter`) or ``None``
251 if the process was created with ``stdin=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200252
253 .. attribute:: stdout
254
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700255 Standard output stream (:class:`StreamReader`) or ``None``
256 if the process was created with ``stdout=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200257
258 .. attribute:: stderr
259
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700260 Standard error stream (:class:`StreamReader`) or ``None``
261 if the process was created with ``stderr=None``.
Victor Stinner39892052014-10-14 00:52:07 +0200262
263 .. warning::
264
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700265 Use the :meth:`communicate` method rather than
266 :attr:`process.stdin.write() <stdin>`,
267 :attr:`await process.stdout.read() <stdout>` or
268 :attr:`await process.stderr.read <stderr>`
269 to avoid deadlocks due to streams pausing reading or writing
270 and blocking the child process.
Victor Stinner39892052014-10-14 00:52:07 +0200271
272 .. attribute:: pid
273
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700274 Process identification number (PID).
Victor Stinner39892052014-10-14 00:52:07 +0200275
276 Note that for processes created by the :func:`create_subprocess_shell`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700277 function, this attribute is the PID of the spawned shell.
Victor Stinner39892052014-10-14 00:52:07 +0200278
279 .. attribute:: returncode
280
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700281 Return code of the process when it exits.
Victor Stinner39892052014-10-14 00:52:07 +0200282
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700283 A ``None`` value indicates that the process has not terminated yet.
284
285 A negative value ``-N`` indicates that the child was terminated
286 by signal ``N`` (Unix only).
Victor Stinner7bdf7862014-03-16 21:29:31 +0100287
Victor Stinnere48d4db2014-02-03 23:26:28 +0100288
Victor Stinner399c59d2015-01-09 01:32:02 +0100289.. _asyncio-subprocess-threads:
290
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700291Subprocess and Threads
Victor Stinner5492d352015-09-02 15:39:01 +0200292----------------------
Victor Stinner399c59d2015-01-09 01:32:02 +0100293
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700294asyncio built-in event loops support running subprocesses from
295different threads, but there are the following limitations:
Victor Stinner399c59d2015-01-09 01:32:02 +0100296
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700297* An event loop must run in the main thread.
Victor Stinner399c59d2015-01-09 01:32:02 +0100298
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700299* The child watcher must be instantiated in the main thread,
300 before executing subprocesses from other threads. Call the
301 :func:`get_child_watcher` function in the main thread to instantiate
302 the child watcher.
303
304Note, that alternative event loop implementations might not share
305the above limitations; please refer to their documentation.
Victor Stinner83704962015-02-25 14:24:15 +0100306
Victor Stinner399c59d2015-01-09 01:32:02 +0100307.. seealso::
308
309 The :ref:`Concurrency and multithreading in asyncio
310 <asyncio-multithreading>` section.
311
312
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700313Examples
314--------
Victor Stinnere48d4db2014-02-03 23:26:28 +0100315
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700316An example using the :class:`~asyncio.subprocess.Process` class to
317control a subprocess and the :class:`StreamReader` class to read from
318the *stdout*.
Victor Stinner39892052014-10-14 00:52:07 +0200319
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700320The subprocess is created by the :func:`create_subprocess_exec`
Victor Stinner39892052014-10-14 00:52:07 +0200321function::
322
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700323 import asyncio
Victor Stinner39892052014-10-14 00:52:07 +0200324 import sys
325
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400326 async def get_date():
Victor Stinner39892052014-10-14 00:52:07 +0200327 code = 'import datetime; print(datetime.datetime.now())'
328
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700329 # Create the subprocess; redirect the standard output
330 # into a pipe.
Andrew Svetlov88743422017-12-11 17:35:49 +0200331 proc = await asyncio.create_subprocess_exec(
332 sys.executable, '-c', code,
333 stdout=asyncio.subprocess.PIPE)
Victor Stinner39892052014-10-14 00:52:07 +0200334
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700335 # Read one line of output.
Andrew Svetlov88743422017-12-11 17:35:49 +0200336 data = await proc.stdout.readline()
Victor Stinner39892052014-10-14 00:52:07 +0200337 line = data.decode('ascii').rstrip()
338
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700339 # Wait for the subprocess exit.
Andrew Svetlov88743422017-12-11 17:35:49 +0200340 await proc.wait()
Victor Stinner39892052014-10-14 00:52:07 +0200341 return line
342
343 if sys.platform == "win32":
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700344 asyncio.set_event_loop_policy(
345 asyncio.WindowsProactorEventLoopPolicy())
Victor Stinner39892052014-10-14 00:52:07 +0200346
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700347 date = asyncio.run(get_date())
348 print(f"Current date: {date}")
349
350
351See also the :ref:`same example <asyncio-subprocess-proto-example>`
352written using low-level APIs.