blob: 1cbfcf21a7f236668af8b133f730bd1a08ad68c5 [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
Victor Stinner08444382014-02-02 22:43:39 +01005Subprocess
6==========
7
Victor Stinneraea82292014-07-08 23:42:38 +02008Windows event loop
9------------------
Victor Stinner984600f2014-03-25 09:40:26 +010010
Victor Stinneraea82292014-07-08 23:42:38 +020011On Windows, the default event loop is :class:`SelectorEventLoop` which does not
12support subprocesses. :class:`ProactorEventLoop` should be used instead.
13Example to use it on Windows::
Victor Stinner984600f2014-03-25 09:40:26 +010014
Victor Stinneraea82292014-07-08 23:42:38 +020015 import asyncio, os
16
17 if os.name == 'nt':
18 loop = asyncio.ProactorEventLoop()
19 asyncio.set_event_loop(loop)
Victor Stinner984600f2014-03-25 09:40:26 +010020
Victor Stinner778015b2014-07-11 12:13:39 +020021.. seealso::
22
23 :ref:`Available event loops <asyncio-event-loops>` and :ref:`Platform
24 support <asyncio-platform-support>`.
25
Victor Stinner984600f2014-03-25 09:40:26 +010026
27Create a subprocess: high-level API using Process
28-------------------------------------------------
Victor Stinner08444382014-02-02 22:43:39 +010029
Victor Stinner39892052014-10-14 00:52:07 +020030.. function:: create_subprocess_exec(\*args, stdin=None, stdout=None, stderr=None, loop=None, limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010031
Victor Stinner39892052014-10-14 00:52:07 +020032 Create a subprocess.
Victor Stinner08444382014-02-02 22:43:39 +010033
Victor Stinner39892052014-10-14 00:52:07 +020034 The *limit* parameter sets the buffer limit passed to the
35 :class:`StreamReader`. See :meth:`BaseEventLoop.subprocess_exec` for other
36 parameters.
37
38 Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner984600f2014-03-25 09:40:26 +010039
Victor Stinner2fb3b822014-03-13 10:58:03 +010040 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner08444382014-02-02 22:43:39 +010041
Victor Stinner39892052014-10-14 00:52:07 +020042.. function:: create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, loop=None, limit=None, \*\*kwds)
Victor Stinner08444382014-02-02 22:43:39 +010043
Victor Stinner39892052014-10-14 00:52:07 +020044 Run the shell command *cmd*.
Victor Stinner08444382014-02-02 22:43:39 +010045
Victor Stinner39892052014-10-14 00:52:07 +020046 The *limit* parameter sets the buffer limit passed to the
47 :class:`StreamReader`. See :meth:`BaseEventLoop.subprocess_shell` for other
48 parameters.
49
50 Return a :class:`~asyncio.subprocess.Process` instance.
51
52 It is the application's responsibility to ensure that all whitespace and
53 metacharacters are quoted appropriately to avoid `shell injection
54 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
55 vulnerabilities. The :func:`shlex.quote` function can be used to properly
56 escape whitespace and shell metacharacters in strings that are going to be
57 used to construct shell commands.
Victor Stinner984600f2014-03-25 09:40:26 +010058
Victor Stinner2fb3b822014-03-13 10:58:03 +010059 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner08444382014-02-02 22:43:39 +010060
61Use the :meth:`BaseEventLoop.connect_read_pipe` and
62:meth:`BaseEventLoop.connect_write_pipe` methods to connect pipes.
63
Victor Stinner984600f2014-03-25 09:40:26 +010064
65Create a subprocess: low-level API using subprocess.Popen
66---------------------------------------------------------
67
68Run subprocesses asynchronously using the :mod:`subprocess` module.
69
70.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
71
Victor Stinner6bfd8542014-06-19 12:50:27 +020072 Create a subprocess from one or more string arguments (character strings or
73 bytes strings encoded to the :ref:`filesystem encoding
74 <filesystem-encoding>`), where the first string
Victor Stinner984600f2014-03-25 09:40:26 +010075 specifies the program to execute, and the remaining strings specify the
76 program's arguments. (Thus, together the string arguments form the
77 ``sys.argv`` value of the program, assuming it is a Python script.) This is
78 similar to the standard library :class:`subprocess.Popen` class called with
79 shell=False and the list of strings passed as the first argument;
80 however, where :class:`~subprocess.Popen` takes a single argument which is
81 list of strings, :func:`subprocess_exec` takes multiple string arguments.
82
Victor Stinner3c950622014-10-14 00:02:10 +020083 The *protocol_factory* must instanciate a subclass of the
84 :class:`asyncio.SubprocessProtocol` class.
85
Victor Stinner984600f2014-03-25 09:40:26 +010086 Other parameters:
87
88 * *stdin*: Either a file-like object representing the pipe to be connected
89 to the subprocess's standard input stream using
90 :meth:`~BaseEventLoop.connect_write_pipe`, or the constant
91 :const:`subprocess.PIPE` (the default). By default a new pipe will be
92 created and connected.
93
94 * *stdout*: Either a file-like object representing the pipe to be connected
95 to the subprocess's standard output stream using
96 :meth:`~BaseEventLoop.connect_read_pipe`, or the constant
97 :const:`subprocess.PIPE` (the default). By default a new pipe will be
98 created and connected.
99
100 * *stderr*: Either a file-like object representing the pipe to be connected
101 to the subprocess's standard error stream using
102 :meth:`~BaseEventLoop.connect_read_pipe`, or one of the constants
103 :const:`subprocess.PIPE` (the default) or :const:`subprocess.STDOUT`.
104 By default a new pipe will be created and connected. When
105 :const:`subprocess.STDOUT` is specified, the subprocess's standard error
106 stream will be connected to the same pipe as the standard output stream.
107
108 * All other keyword arguments are passed to :class:`subprocess.Popen`
109 without interpretation, except for *bufsize*, *universal_newlines* and
110 *shell*, which should not be specified at all.
111
112 Returns a pair of ``(transport, protocol)``, where *transport* is an
113 instance of :class:`BaseSubprocessTransport`.
114
115 This method is a :ref:`coroutine <coroutine>`.
116
117 See the constructor of the :class:`subprocess.Popen` class for parameters.
118
119.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
120
Victor Stinner6bfd8542014-06-19 12:50:27 +0200121 Create a subprocess from *cmd*, which is a character string or a bytes
122 string encoded to the :ref:`filesystem encoding <filesystem-encoding>`,
123 using the platform's "shell" syntax. This is similar to the standard library
Victor Stinner984600f2014-03-25 09:40:26 +0100124 :class:`subprocess.Popen` class called with ``shell=True``.
125
Victor Stinner3c950622014-10-14 00:02:10 +0200126 The *protocol_factory* must instanciate a subclass of the
127 :class:`asyncio.SubprocessProtocol` class.
128
Victor Stinner984600f2014-03-25 09:40:26 +0100129 See :meth:`~BaseEventLoop.subprocess_exec` for more details about
130 the remaining arguments.
131
132 Returns a pair of ``(transport, protocol)``, where *transport* is an
133 instance of :class:`BaseSubprocessTransport`.
134
Victor Stinner39892052014-10-14 00:52:07 +0200135 It is the application's responsibility to ensure that all whitespace and
136 metacharacters are quoted appropriately to avoid `shell injection
137 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
138 vulnerabilities. The :func:`shlex.quote` function can be used to properly
139 escape whitespace and shell metacharacters in strings that are going to be
140 used to construct shell commands.
Victor Stinner984600f2014-03-25 09:40:26 +0100141
Victor Stinner39892052014-10-14 00:52:07 +0200142 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner984600f2014-03-25 09:40:26 +0100143
Victor Stinner08444382014-02-02 22:43:39 +0100144.. seealso::
145
Victor Stinner984600f2014-03-25 09:40:26 +0100146 The :meth:`BaseEventLoop.connect_read_pipe` and
147 :meth:`BaseEventLoop.connect_write_pipe` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100148
149
150Constants
151---------
152
153.. data:: asyncio.subprocess.PIPE
154
155 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
156 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
157 indicates that a pipe to the standard stream should be opened.
158
159.. data:: asyncio.subprocess.STDOUT
160
161 Special value that can be used as the *stderr* argument to
162 :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
163 indicates that standard error should go into the same handle as standard
164 output.
165
166.. data:: asyncio.subprocess.DEVNULL
167
Victor Stinner72804862014-03-21 11:44:49 +0100168 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
169 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
170 indicates that the special file :data:`os.devnull` will be used.
Victor Stinner08444382014-02-02 22:43:39 +0100171
172
173Process
174-------
175
176.. class:: asyncio.subprocess.Process
177
Victor Stinner39892052014-10-14 00:52:07 +0200178 A subprocess created by the :func:`create_subprocess_exec` or the
179 :func:`create_subprocess_shell` function.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100180
Victor Stinner39892052014-10-14 00:52:07 +0200181 The API of the :class:`~asyncio.subprocess.Process` class was designed to be
182 closed the API of the :class:`subprocess.Popen` class, but they are some
183 differences:
Victor Stinnerb79eb052014-02-03 23:08:14 +0100184
Victor Stinner39892052014-10-14 00:52:07 +0200185 * There is no explicit :meth:`~subprocess.Popen.poll` method
186 * The :meth:`~subprocess.Popen.communicate` and
187 :meth:`~subprocess.Popen.wait` methods don't take a *timeout* parameter:
188 use the :func:`wait_for` function
189 * The *universal_newlines* parameter is not supported (only bytes strings
190 are supported)
191 * The :meth:`~asyncio.subprocess.Process.wait` method of
192 the :class:`~asyncio.subprocess.Process` class is asynchronous whereas the
193 :meth:`~subprocess.Popen.wait` method of the :class:`~subprocess.Popen`
194 class is implemented as a busy loop.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100195
Victor Stinner39892052014-10-14 00:52:07 +0200196 .. method:: wait()
Victor Stinnerb79eb052014-02-03 23:08:14 +0100197
Victor Stinner39892052014-10-14 00:52:07 +0200198 Wait for child process to terminate. Set and return :attr:`returncode`
199 attribute.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100200
Victor Stinner39892052014-10-14 00:52:07 +0200201 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerb79eb052014-02-03 23:08:14 +0100202
Victor Stinner39892052014-10-14 00:52:07 +0200203 .. note::
Victor Stinner08444382014-02-02 22:43:39 +0100204
Victor Stinner39892052014-10-14 00:52:07 +0200205 This will deadlock when using ``stdout=PIPE`` or ``stderr=PIPE`` and
206 the child process generates enough output to a pipe such that it
207 blocks waiting for the OS pipe buffer to accept more data. Use the
208 :meth:`communicate` method when using pipes to avoid that.
Victor Stinner08444382014-02-02 22:43:39 +0100209
Victor Stinner08444382014-02-02 22:43:39 +0100210 .. method:: communicate(input=None)
211
212 Interact with process: Send data to stdin. Read data from stdout and
213 stderr, until end-of-file is reached. Wait for process to terminate.
214 The optional *input* argument should be data to be sent to the child
215 process, or ``None``, if no data should be sent to the child. The type
216 of *input* must be bytes.
217
Victor Stinner39892052014-10-14 00:52:07 +0200218 :meth:`communicate` returns a tuple ``(stdout_data, stderr_data)``.
219
Victor Stinnerd55b54d2014-07-17 13:12:03 +0200220 If a :exc:`BrokenPipeError` or :exc:`ConnectionResetError` exception is
221 raised when writing *input* into stdin, the exception is ignored. It
222 occurs when the process exits before all data are written into stdin.
Victor Stinnercc996b52014-07-17 12:25:27 +0200223
Victor Stinner08444382014-02-02 22:43:39 +0100224 Note that if you want to send data to the process's stdin, you need to
Victor Stinner0c3949c2014-02-09 02:51:40 +0100225 create the Process object with ``stdin=PIPE``. Similarly, to get anything
Victor Stinner08444382014-02-02 22:43:39 +0100226 other than ``None`` in the result tuple, you need to give ``stdout=PIPE``
227 and/or ``stderr=PIPE`` too.
228
Victor Stinner39892052014-10-14 00:52:07 +0200229 This method is a :ref:`coroutine <coroutine>`.
230
Victor Stinner08444382014-02-02 22:43:39 +0100231 .. note::
232
233 The data read is buffered in memory, so do not use this method if the
234 data size is large or unlimited.
235
Victor Stinnercc996b52014-07-17 12:25:27 +0200236 .. versionchanged:: 3.4.2
Victor Stinnerd55b54d2014-07-17 13:12:03 +0200237 The method now ignores :exc:`BrokenPipeError` and
238 :exc:`ConnectionResetError`.
Victor Stinnercc996b52014-07-17 12:25:27 +0200239
Brian Curtina1afeec2014-02-08 18:36:14 -0600240 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100241
242 Sends the signal *signal* to the child process.
243
244 .. note::
245
246 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
247 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
248 started with a *creationflags* parameter which includes
249 ``CREATE_NEW_PROCESS_GROUP``.
250
251 .. method:: terminate()
252
253 Stop the child. On Posix OSs the method sends :py:data:`signal.SIGTERM`
254 to the child. On Windows the Win32 API function
255 :c:func:`TerminateProcess` is called to stop the child.
256
Victor Stinner39892052014-10-14 00:52:07 +0200257 .. method:: kill()
Victor Stinner08444382014-02-02 22:43:39 +0100258
Victor Stinner39892052014-10-14 00:52:07 +0200259 Kills the child. On Posix OSs the function sends :py:data:`SIGKILL` to
260 the child. On Windows :meth:`kill` is an alias for :meth:`terminate`.
Victor Stinner08444382014-02-02 22:43:39 +0100261
Victor Stinner39892052014-10-14 00:52:07 +0200262 .. attribute:: stdin
263
264 Standard input stream (:class:`StreamWriter`), ``None`` if the process
265 was created with ``stdin=None``.
266
267 .. attribute:: stdout
268
269 Standard output stream (:class:`StreamReader`), ``None`` if the process
270 was created with ``stdout=None``.
271
272 .. attribute:: stderr
273
274 Standard error stream (:class:`StreamReader`), ``None`` if the process
275 was created with ``stderr=None``.
276
277 .. warning::
278
279 Use the :meth:`communicate` method rather than :attr:`.stdin.write
280 <stdin>`, :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>`
281 to avoid deadlocks due to streams pausing reading or writing and blocking
282 the child process.
283
284 .. attribute:: pid
285
286 The identifier of the process.
287
288 Note that for processes created by the :func:`create_subprocess_shell`
289 function, this attribute is the process identifier of the spawned shell.
290
291 .. attribute:: returncode
292
293 Return code of the process when it exited. A ``None`` value indicates
294 that the process has not terminated yet.
295
296 A negative value ``-N`` indicates that the child was terminated by signal
297 ``N`` (Unix only).
Victor Stinner7bdf7862014-03-16 21:29:31 +0100298
Victor Stinnere48d4db2014-02-03 23:26:28 +0100299
Victor Stinner39892052014-10-14 00:52:07 +0200300Subprocess examples
301===================
Victor Stinnere48d4db2014-02-03 23:26:28 +0100302
Victor Stinner39892052014-10-14 00:52:07 +0200303Subprocess using transport and protocol
304---------------------------------------
305
306Example of a subprocess protocol using to get the output of a subprocess and to
307wait for the subprocess exit. The subprocess is created by the
308:meth:`BaseEventLoop.subprocess_exec` method::
Victor Stinnere48d4db2014-02-03 23:26:28 +0100309
310 import asyncio
311 import sys
Victor Stinner39892052014-10-14 00:52:07 +0200312
313 class DateProtocol(asyncio.SubprocessProtocol):
314 def __init__(self, exit_future):
315 self.exit_future = exit_future
316 self.output = bytearray()
317
318 def pipe_data_received(self, fd, data):
319 self.output.extend(data)
320
321 def process_exited(self):
322 self.exit_future.set_result(True)
Victor Stinnere48d4db2014-02-03 23:26:28 +0100323
324 @asyncio.coroutine
Victor Stinner39892052014-10-14 00:52:07 +0200325 def get_date(loop):
326 code = 'import datetime; print(datetime.datetime.now())'
327 exit_future = asyncio.Future(loop=loop)
Victor Stinnere48d4db2014-02-03 23:26:28 +0100328
Victor Stinner39892052014-10-14 00:52:07 +0200329 # Create the subprocess controlled by the protocol DateProtocol,
330 # redirect the standard output into a pipe
331 create = loop.subprocess_exec(lambda: DateProtocol(exit_future),
332 sys.executable, '-c', code,
333 stdin=None, stderr=None)
334 transport, protocol = yield from create
335
336 # Wait for the subprocess exit using the process_exited() method
337 # of the protocol
338 yield from exit_future
339
340 # Close the stdout pipe
341 transport.close()
342
343 # Read the output which was collected by the pipe_data_received()
344 # method of the protocol
345 data = bytes(protocol.output)
346 return data.decode('ascii').rstrip()
347
348 if sys.platform == "win32":
Victor Stinner6bc23962014-03-21 11:56:40 +0100349 loop = asyncio.ProactorEventLoop()
350 asyncio.set_event_loop(loop)
351 else:
352 loop = asyncio.get_event_loop()
Victor Stinner39892052014-10-14 00:52:07 +0200353
354 date = loop.run_until_complete(get_date(loop))
355 print("Current date: %s" % date)
356 loop.close()
357
358
359Subprocess using streams
360------------------------
361
362Example using the :class:`~asyncio.subprocess.Process` class to control the
363subprocess and the :class:`StreamReader` class to read from the standard
364output. The subprocess is created by the :func:`create_subprocess_exec`
365function::
366
367 import asyncio.subprocess
368 import sys
369
370 @asyncio.coroutine
371 def get_date():
372 code = 'import datetime; print(datetime.datetime.now())'
373
374 # Create the subprocess, redirect the standard output into a pipe
375 create = asyncio.create_subprocess_exec(sys.executable, '-c', code,
376 stdout=asyncio.subprocess.PIPE)
377 proc = yield from create
378
379 # Read one line of output
380 data = yield from proc.stdout.readline()
381 line = data.decode('ascii').rstrip()
382
383 # Wait for the subprocess exit
384 yield from proc.wait()
385 return line
386
387 if sys.platform == "win32":
388 loop = asyncio.ProactorEventLoop()
389 asyncio.set_event_loop(loop)
Victor Stinnere48d4db2014-02-03 23:26:28 +0100390 else:
Victor Stinner39892052014-10-14 00:52:07 +0200391 loop = asyncio.get_event_loop()
392
393 date = loop.run_until_complete(get_date())
394 print("Current date: %s" % date)
Victor Stinnere48d4db2014-02-03 23:26:28 +0100395 loop.close()