blob: b6532618266b5f67b1f380c541944a512354c780 [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
30.. function:: create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, loop=None, limit=None, \*\*kwds)
31
Victor Stinner6bfd8542014-06-19 12:50:27 +020032 Run the shell command *cmd*. See :meth:`BaseEventLoop.subprocess_shell` for
33 parameters. Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner08444382014-02-02 22:43:39 +010034
Victor Stinner984600f2014-03-25 09:40:26 +010035 The optional *limit* parameter sets the buffer limit passed to the
36 :class:`StreamReader`.
37
Victor Stinner2fb3b822014-03-13 10:58:03 +010038 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner08444382014-02-02 22:43:39 +010039
40.. function:: create_subprocess_exec(\*args, stdin=None, stdout=None, stderr=None, loop=None, limit=None, \*\*kwds)
41
Victor Stinner6bfd8542014-06-19 12:50:27 +020042 Create a subprocess. See :meth:`BaseEventLoop.subprocess_exec` for
43 parameters. Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner08444382014-02-02 22:43:39 +010044
Victor Stinner984600f2014-03-25 09:40:26 +010045 The optional *limit* parameter sets the buffer limit passed to the
46 :class:`StreamReader`.
47
Victor Stinner2fb3b822014-03-13 10:58:03 +010048 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner08444382014-02-02 22:43:39 +010049
50Use the :meth:`BaseEventLoop.connect_read_pipe` and
51:meth:`BaseEventLoop.connect_write_pipe` methods to connect pipes.
52
Victor Stinner984600f2014-03-25 09:40:26 +010053
54Create a subprocess: low-level API using subprocess.Popen
55---------------------------------------------------------
56
57Run subprocesses asynchronously using the :mod:`subprocess` module.
58
59.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
60
Victor Stinner6bfd8542014-06-19 12:50:27 +020061 Create a subprocess from one or more string arguments (character strings or
62 bytes strings encoded to the :ref:`filesystem encoding
63 <filesystem-encoding>`), where the first string
Victor Stinner984600f2014-03-25 09:40:26 +010064 specifies the program to execute, and the remaining strings specify the
65 program's arguments. (Thus, together the string arguments form the
66 ``sys.argv`` value of the program, assuming it is a Python script.) This is
67 similar to the standard library :class:`subprocess.Popen` class called with
68 shell=False and the list of strings passed as the first argument;
69 however, where :class:`~subprocess.Popen` takes a single argument which is
70 list of strings, :func:`subprocess_exec` takes multiple string arguments.
71
72 Other parameters:
73
74 * *stdin*: Either a file-like object representing the pipe to be connected
75 to the subprocess's standard input stream using
76 :meth:`~BaseEventLoop.connect_write_pipe`, or the constant
77 :const:`subprocess.PIPE` (the default). By default a new pipe will be
78 created and connected.
79
80 * *stdout*: Either a file-like object representing the pipe to be connected
81 to the subprocess's standard output stream using
82 :meth:`~BaseEventLoop.connect_read_pipe`, or the constant
83 :const:`subprocess.PIPE` (the default). By default a new pipe will be
84 created and connected.
85
86 * *stderr*: Either a file-like object representing the pipe to be connected
87 to the subprocess's standard error stream using
88 :meth:`~BaseEventLoop.connect_read_pipe`, or one of the constants
89 :const:`subprocess.PIPE` (the default) or :const:`subprocess.STDOUT`.
90 By default a new pipe will be created and connected. When
91 :const:`subprocess.STDOUT` is specified, the subprocess's standard error
92 stream will be connected to the same pipe as the standard output stream.
93
94 * All other keyword arguments are passed to :class:`subprocess.Popen`
95 without interpretation, except for *bufsize*, *universal_newlines* and
96 *shell*, which should not be specified at all.
97
98 Returns a pair of ``(transport, protocol)``, where *transport* is an
99 instance of :class:`BaseSubprocessTransport`.
100
101 This method is a :ref:`coroutine <coroutine>`.
102
103 See the constructor of the :class:`subprocess.Popen` class for parameters.
104
105.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
106
Victor Stinner6bfd8542014-06-19 12:50:27 +0200107 Create a subprocess from *cmd*, which is a character string or a bytes
108 string encoded to the :ref:`filesystem encoding <filesystem-encoding>`,
109 using the platform's "shell" syntax. This is similar to the standard library
Victor Stinner984600f2014-03-25 09:40:26 +0100110 :class:`subprocess.Popen` class called with ``shell=True``.
111
112 See :meth:`~BaseEventLoop.subprocess_exec` for more details about
113 the remaining arguments.
114
115 Returns a pair of ``(transport, protocol)``, where *transport* is an
116 instance of :class:`BaseSubprocessTransport`.
117
118 This method is a :ref:`coroutine <coroutine>`.
119
120 See the constructor of the :class:`subprocess.Popen` class for parameters.
121
Victor Stinner08444382014-02-02 22:43:39 +0100122.. seealso::
123
Victor Stinner984600f2014-03-25 09:40:26 +0100124 The :meth:`BaseEventLoop.connect_read_pipe` and
125 :meth:`BaseEventLoop.connect_write_pipe` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100126
127
128Constants
129---------
130
131.. data:: asyncio.subprocess.PIPE
132
133 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
134 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
135 indicates that a pipe to the standard stream should be opened.
136
137.. data:: asyncio.subprocess.STDOUT
138
139 Special value that can be used as the *stderr* argument to
140 :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
141 indicates that standard error should go into the same handle as standard
142 output.
143
144.. data:: asyncio.subprocess.DEVNULL
145
Victor Stinner72804862014-03-21 11:44:49 +0100146 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
147 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
148 indicates that the special file :data:`os.devnull` will be used.
Victor Stinner08444382014-02-02 22:43:39 +0100149
150
151Process
152-------
153
154.. class:: asyncio.subprocess.Process
155
Victor Stinnerb79eb052014-02-03 23:08:14 +0100156 .. attribute:: pid
157
158 The identifier of the process.
159
160 Note that if you set the *shell* argument to ``True``, this is the
161 process identifier of the spawned shell.
162
163 .. attribute:: returncode
164
165 Return code of the process when it exited. A ``None`` value indicates
166 that the process has not terminated yet.
167
168 A negative value ``-N`` indicates that the child was terminated by signal
169 ``N`` (Unix only).
170
Victor Stinner08444382014-02-02 22:43:39 +0100171 .. attribute:: stdin
172
173 Standard input stream (write), ``None`` if the process was created with
174 ``stdin=None``.
175
176 .. attribute:: stdout
177
178 Standard output stream (read), ``None`` if the process was created with
179 ``stdout=None``.
180
181 .. attribute:: stderr
182
183 Standard error stream (read), ``None`` if the process was created with
184 ``stderr=None``.
185
Victor Stinner08444382014-02-02 22:43:39 +0100186 .. method:: communicate(input=None)
187
188 Interact with process: Send data to stdin. Read data from stdout and
189 stderr, until end-of-file is reached. Wait for process to terminate.
190 The optional *input* argument should be data to be sent to the child
191 process, or ``None``, if no data should be sent to the child. The type
192 of *input* must be bytes.
193
Victor Stinnerd55b54d2014-07-17 13:12:03 +0200194 If a :exc:`BrokenPipeError` or :exc:`ConnectionResetError` exception is
195 raised when writing *input* into stdin, the exception is ignored. It
196 occurs when the process exits before all data are written into stdin.
Victor Stinnercc996b52014-07-17 12:25:27 +0200197
Victor Stinner08444382014-02-02 22:43:39 +0100198 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
199
200 Note that if you want to send data to the process's stdin, you need to
Victor Stinner0c3949c2014-02-09 02:51:40 +0100201 create the Process object with ``stdin=PIPE``. Similarly, to get anything
Victor Stinner08444382014-02-02 22:43:39 +0100202 other than ``None`` in the result tuple, you need to give ``stdout=PIPE``
203 and/or ``stderr=PIPE`` too.
204
205 .. note::
206
207 The data read is buffered in memory, so do not use this method if the
208 data size is large or unlimited.
209
Victor Stinner7bdf7862014-03-16 21:29:31 +0100210 This method is a :ref:`coroutine <coroutine>`.
211
Victor Stinnercc996b52014-07-17 12:25:27 +0200212 .. versionchanged:: 3.4.2
Victor Stinnerd55b54d2014-07-17 13:12:03 +0200213 The method now ignores :exc:`BrokenPipeError` and
214 :exc:`ConnectionResetError`.
Victor Stinnercc996b52014-07-17 12:25:27 +0200215
Victor Stinner08444382014-02-02 22:43:39 +0100216 .. method:: kill()
217
218 Kills the child. On Posix OSs the function sends :py:data:`SIGKILL` to
219 the child. On Windows :meth:`kill` is an alias for :meth:`terminate`.
220
Brian Curtina1afeec2014-02-08 18:36:14 -0600221 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100222
223 Sends the signal *signal* to the child process.
224
225 .. note::
226
227 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
228 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
229 started with a *creationflags* parameter which includes
230 ``CREATE_NEW_PROCESS_GROUP``.
231
232 .. method:: terminate()
233
234 Stop the child. On Posix OSs the method sends :py:data:`signal.SIGTERM`
235 to the child. On Windows the Win32 API function
236 :c:func:`TerminateProcess` is called to stop the child.
237
Victor Stinner7bdf7862014-03-16 21:29:31 +0100238 .. method:: wait():
Victor Stinner08444382014-02-02 22:43:39 +0100239
240 Wait for child process to terminate. Set and return :attr:`returncode`
241 attribute.
242
Victor Stinner7bdf7862014-03-16 21:29:31 +0100243 This method is a :ref:`coroutine <coroutine>`.
244
Victor Stinnere48d4db2014-02-03 23:26:28 +0100245
246Example
247-------
248
249Implement a function similar to :func:`subprocess.getstatusoutput`, except that
250it does not use a shell. Get the output of the "python -m platform" command and
251display the output::
252
253 import asyncio
Victor Stinner6bc23962014-03-21 11:56:40 +0100254 import os
Victor Stinnere48d4db2014-02-03 23:26:28 +0100255 import sys
256 from asyncio import subprocess
257
258 @asyncio.coroutine
259 def getstatusoutput(*args):
260 proc = yield from asyncio.create_subprocess_exec(
261 *args,
262 stdout=subprocess.PIPE,
263 stderr=subprocess.STDOUT)
264 try:
265 stdout, _ = yield from proc.communicate()
266 except:
267 proc.kill()
268 yield from proc.wait()
269 raise
270 exitcode = yield from proc.wait()
271 return (exitcode, stdout)
272
Victor Stinner6bc23962014-03-21 11:56:40 +0100273 if os.name == 'nt':
274 loop = asyncio.ProactorEventLoop()
275 asyncio.set_event_loop(loop)
276 else:
277 loop = asyncio.get_event_loop()
Victor Stinnere48d4db2014-02-03 23:26:28 +0100278 coro = getstatusoutput(sys.executable, '-m', 'platform')
279 exitcode, stdout = loop.run_until_complete(coro)
280 if not exitcode:
281 stdout = stdout.decode('ascii').rstrip()
282 print("Platform: %s" % stdout)
283 else:
Victor Stinnerb0539b22014-05-12 23:25:09 +0200284 print("Python failed with exit code %s:" % exitcode, flush=True)
Victor Stinnere48d4db2014-02-03 23:26:28 +0100285 sys.stdout.buffer.write(stdout)
286 sys.stdout.buffer.flush()
287 loop.close()