blob: 3f57a8211b52e7dbcf0004a26202bc4f37b4c2bc [file] [log] [blame]
Victor Stinner08444382014-02-02 22:43:39 +01001.. currentmodule:: asyncio
2
3Subprocess
4==========
5
Victor Stinner984600f2014-03-25 09:40:26 +01006Operating system support
7------------------------
8
9On Windows, the default event loop uses :class:`selectors.SelectSelector`
10which only supports sockets. The :class:`ProactorEventLoop` should be used to
Guido van Rossum5280d2e2014-05-05 07:34:56 -070011support subprocesses. However, the latter does not support SSL.
Victor Stinner984600f2014-03-25 09:40:26 +010012
13On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
14does not support character devices like PTY, whereas it is used by the
15default event loop. The :class:`SelectorEventLoop` can be used with
16:class:`SelectSelector` or :class:`PollSelector` to handle character
17devices on Mac OS X 10.6 (Snow Leopard) and later.
18
19
20Create a subprocess: high-level API using Process
21-------------------------------------------------
Victor Stinner08444382014-02-02 22:43:39 +010022
23.. function:: create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, loop=None, limit=None, \*\*kwds)
24
Victor Stinner6bfd8542014-06-19 12:50:27 +020025 Run the shell command *cmd*. See :meth:`BaseEventLoop.subprocess_shell` for
26 parameters. Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner08444382014-02-02 22:43:39 +010027
Victor Stinner984600f2014-03-25 09:40:26 +010028 The optional *limit* parameter sets the buffer limit passed to the
29 :class:`StreamReader`.
30
Victor Stinner2fb3b822014-03-13 10:58:03 +010031 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner08444382014-02-02 22:43:39 +010032
33.. function:: create_subprocess_exec(\*args, stdin=None, stdout=None, stderr=None, loop=None, limit=None, \*\*kwds)
34
Victor Stinner6bfd8542014-06-19 12:50:27 +020035 Create a subprocess. See :meth:`BaseEventLoop.subprocess_exec` for
36 parameters. Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner08444382014-02-02 22:43:39 +010037
Victor Stinner984600f2014-03-25 09:40:26 +010038 The optional *limit* parameter sets the buffer limit passed to the
39 :class:`StreamReader`.
40
Victor Stinner2fb3b822014-03-13 10:58:03 +010041 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner08444382014-02-02 22:43:39 +010042
43Use the :meth:`BaseEventLoop.connect_read_pipe` and
44:meth:`BaseEventLoop.connect_write_pipe` methods to connect pipes.
45
Victor Stinner984600f2014-03-25 09:40:26 +010046
47Create a subprocess: low-level API using subprocess.Popen
48---------------------------------------------------------
49
50Run subprocesses asynchronously using the :mod:`subprocess` module.
51
52.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
53
Victor Stinner6bfd8542014-06-19 12:50:27 +020054 Create a subprocess from one or more string arguments (character strings or
55 bytes strings encoded to the :ref:`filesystem encoding
56 <filesystem-encoding>`), where the first string
Victor Stinner984600f2014-03-25 09:40:26 +010057 specifies the program to execute, and the remaining strings specify the
58 program's arguments. (Thus, together the string arguments form the
59 ``sys.argv`` value of the program, assuming it is a Python script.) This is
60 similar to the standard library :class:`subprocess.Popen` class called with
61 shell=False and the list of strings passed as the first argument;
62 however, where :class:`~subprocess.Popen` takes a single argument which is
63 list of strings, :func:`subprocess_exec` takes multiple string arguments.
64
65 Other parameters:
66
67 * *stdin*: Either a file-like object representing the pipe to be connected
68 to the subprocess's standard input stream using
69 :meth:`~BaseEventLoop.connect_write_pipe`, or the constant
70 :const:`subprocess.PIPE` (the default). By default a new pipe will be
71 created and connected.
72
73 * *stdout*: Either a file-like object representing the pipe to be connected
74 to the subprocess's standard output stream using
75 :meth:`~BaseEventLoop.connect_read_pipe`, or the constant
76 :const:`subprocess.PIPE` (the default). By default a new pipe will be
77 created and connected.
78
79 * *stderr*: Either a file-like object representing the pipe to be connected
80 to the subprocess's standard error stream using
81 :meth:`~BaseEventLoop.connect_read_pipe`, or one of the constants
82 :const:`subprocess.PIPE` (the default) or :const:`subprocess.STDOUT`.
83 By default a new pipe will be created and connected. When
84 :const:`subprocess.STDOUT` is specified, the subprocess's standard error
85 stream will be connected to the same pipe as the standard output stream.
86
87 * All other keyword arguments are passed to :class:`subprocess.Popen`
88 without interpretation, except for *bufsize*, *universal_newlines* and
89 *shell*, which should not be specified at all.
90
91 Returns a pair of ``(transport, protocol)``, where *transport* is an
92 instance of :class:`BaseSubprocessTransport`.
93
94 This method is a :ref:`coroutine <coroutine>`.
95
96 See the constructor of the :class:`subprocess.Popen` class for parameters.
97
98.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
99
Victor Stinner6bfd8542014-06-19 12:50:27 +0200100 Create a subprocess from *cmd*, which is a character string or a bytes
101 string encoded to the :ref:`filesystem encoding <filesystem-encoding>`,
102 using the platform's "shell" syntax. This is similar to the standard library
Victor Stinner984600f2014-03-25 09:40:26 +0100103 :class:`subprocess.Popen` class called with ``shell=True``.
104
105 See :meth:`~BaseEventLoop.subprocess_exec` for more details about
106 the remaining arguments.
107
108 Returns a pair of ``(transport, protocol)``, where *transport* is an
109 instance of :class:`BaseSubprocessTransport`.
110
111 This method is a :ref:`coroutine <coroutine>`.
112
113 See the constructor of the :class:`subprocess.Popen` class for parameters.
114
Victor Stinner08444382014-02-02 22:43:39 +0100115.. seealso::
116
Victor Stinner984600f2014-03-25 09:40:26 +0100117 The :meth:`BaseEventLoop.connect_read_pipe` and
118 :meth:`BaseEventLoop.connect_write_pipe` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100119
120
121Constants
122---------
123
124.. data:: asyncio.subprocess.PIPE
125
126 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
127 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
128 indicates that a pipe to the standard stream should be opened.
129
130.. data:: asyncio.subprocess.STDOUT
131
132 Special value that can be used as the *stderr* argument to
133 :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
134 indicates that standard error should go into the same handle as standard
135 output.
136
137.. data:: asyncio.subprocess.DEVNULL
138
Victor Stinner72804862014-03-21 11:44:49 +0100139 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
140 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
141 indicates that the special file :data:`os.devnull` will be used.
Victor Stinner08444382014-02-02 22:43:39 +0100142
143
144Process
145-------
146
147.. class:: asyncio.subprocess.Process
148
Victor Stinnerb79eb052014-02-03 23:08:14 +0100149 .. attribute:: pid
150
151 The identifier of the process.
152
153 Note that if you set the *shell* argument to ``True``, this is the
154 process identifier of the spawned shell.
155
156 .. attribute:: returncode
157
158 Return code of the process when it exited. A ``None`` value indicates
159 that the process has not terminated yet.
160
161 A negative value ``-N`` indicates that the child was terminated by signal
162 ``N`` (Unix only).
163
Victor Stinner08444382014-02-02 22:43:39 +0100164 .. attribute:: stdin
165
166 Standard input stream (write), ``None`` if the process was created with
167 ``stdin=None``.
168
169 .. attribute:: stdout
170
171 Standard output stream (read), ``None`` if the process was created with
172 ``stdout=None``.
173
174 .. attribute:: stderr
175
176 Standard error stream (read), ``None`` if the process was created with
177 ``stderr=None``.
178
Victor Stinner08444382014-02-02 22:43:39 +0100179 .. method:: communicate(input=None)
180
181 Interact with process: Send data to stdin. Read data from stdout and
182 stderr, until end-of-file is reached. Wait for process to terminate.
183 The optional *input* argument should be data to be sent to the child
184 process, or ``None``, if no data should be sent to the child. The type
185 of *input* must be bytes.
186
187 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
188
189 Note that if you want to send data to the process's stdin, you need to
Victor Stinner0c3949c2014-02-09 02:51:40 +0100190 create the Process object with ``stdin=PIPE``. Similarly, to get anything
Victor Stinner08444382014-02-02 22:43:39 +0100191 other than ``None`` in the result tuple, you need to give ``stdout=PIPE``
192 and/or ``stderr=PIPE`` too.
193
194 .. note::
195
196 The data read is buffered in memory, so do not use this method if the
197 data size is large or unlimited.
198
Victor Stinner7bdf7862014-03-16 21:29:31 +0100199 This method is a :ref:`coroutine <coroutine>`.
200
Victor Stinner08444382014-02-02 22:43:39 +0100201 .. method:: kill()
202
203 Kills the child. On Posix OSs the function sends :py:data:`SIGKILL` to
204 the child. On Windows :meth:`kill` is an alias for :meth:`terminate`.
205
Brian Curtina1afeec2014-02-08 18:36:14 -0600206 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100207
208 Sends the signal *signal* to the child process.
209
210 .. note::
211
212 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
213 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
214 started with a *creationflags* parameter which includes
215 ``CREATE_NEW_PROCESS_GROUP``.
216
217 .. method:: terminate()
218
219 Stop the child. On Posix OSs the method sends :py:data:`signal.SIGTERM`
220 to the child. On Windows the Win32 API function
221 :c:func:`TerminateProcess` is called to stop the child.
222
Victor Stinner7bdf7862014-03-16 21:29:31 +0100223 .. method:: wait():
Victor Stinner08444382014-02-02 22:43:39 +0100224
225 Wait for child process to terminate. Set and return :attr:`returncode`
226 attribute.
227
Victor Stinner7bdf7862014-03-16 21:29:31 +0100228 This method is a :ref:`coroutine <coroutine>`.
229
Victor Stinnere48d4db2014-02-03 23:26:28 +0100230
231Example
232-------
233
234Implement a function similar to :func:`subprocess.getstatusoutput`, except that
235it does not use a shell. Get the output of the "python -m platform" command and
236display the output::
237
238 import asyncio
Victor Stinner6bc23962014-03-21 11:56:40 +0100239 import os
Victor Stinnere48d4db2014-02-03 23:26:28 +0100240 import sys
241 from asyncio import subprocess
242
243 @asyncio.coroutine
244 def getstatusoutput(*args):
245 proc = yield from asyncio.create_subprocess_exec(
246 *args,
247 stdout=subprocess.PIPE,
248 stderr=subprocess.STDOUT)
249 try:
250 stdout, _ = yield from proc.communicate()
251 except:
252 proc.kill()
253 yield from proc.wait()
254 raise
255 exitcode = yield from proc.wait()
256 return (exitcode, stdout)
257
Victor Stinner6bc23962014-03-21 11:56:40 +0100258 if os.name == 'nt':
259 loop = asyncio.ProactorEventLoop()
260 asyncio.set_event_loop(loop)
261 else:
262 loop = asyncio.get_event_loop()
Victor Stinnere48d4db2014-02-03 23:26:28 +0100263 coro = getstatusoutput(sys.executable, '-m', 'platform')
264 exitcode, stdout = loop.run_until_complete(coro)
265 if not exitcode:
266 stdout = stdout.decode('ascii').rstrip()
267 print("Platform: %s" % stdout)
268 else:
Victor Stinnerb0539b22014-05-12 23:25:09 +0200269 print("Python failed with exit code %s:" % exitcode, flush=True)
Victor Stinnere48d4db2014-02-03 23:26:28 +0100270 sys.stdout.buffer.write(stdout)
271 sys.stdout.buffer.flush()
272 loop.close()