blob: 5b4ede61f60884d43526cabfe28484cd2a72ccdb [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 Stinnerde0e1d32014-02-24 13:19:19 +010025 Run the shell command *cmd* given as a string. Return a :class:`~asyncio.subprocess.Process`
Victor Stinner08444382014-02-02 22:43:39 +010026 instance.
27
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 Stinnerde0e1d32014-02-24 13:19:19 +010035 Create a subprocess. Return a :class:`~asyncio.subprocess.Process` instance.
Victor Stinner08444382014-02-02 22:43:39 +010036
Victor Stinner984600f2014-03-25 09:40:26 +010037 The optional *limit* parameter sets the buffer limit passed to the
38 :class:`StreamReader`.
39
Victor Stinner2fb3b822014-03-13 10:58:03 +010040 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner08444382014-02-02 22:43:39 +010041
42Use the :meth:`BaseEventLoop.connect_read_pipe` and
43:meth:`BaseEventLoop.connect_write_pipe` methods to connect pipes.
44
Victor Stinner984600f2014-03-25 09:40:26 +010045
46Create a subprocess: low-level API using subprocess.Popen
47---------------------------------------------------------
48
49Run subprocesses asynchronously using the :mod:`subprocess` module.
50
51.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
52
53 Create a subprocess from one or more string arguments, where the first string
54 specifies the program to execute, and the remaining strings specify the
55 program's arguments. (Thus, together the string arguments form the
56 ``sys.argv`` value of the program, assuming it is a Python script.) This is
57 similar to the standard library :class:`subprocess.Popen` class called with
58 shell=False and the list of strings passed as the first argument;
59 however, where :class:`~subprocess.Popen` takes a single argument which is
60 list of strings, :func:`subprocess_exec` takes multiple string arguments.
61
62 Other parameters:
63
64 * *stdin*: Either a file-like object representing the pipe to be connected
65 to the subprocess's standard input stream using
66 :meth:`~BaseEventLoop.connect_write_pipe`, or the constant
67 :const:`subprocess.PIPE` (the default). By default a new pipe will be
68 created and connected.
69
70 * *stdout*: Either a file-like object representing the pipe to be connected
71 to the subprocess's standard output stream using
72 :meth:`~BaseEventLoop.connect_read_pipe`, or the constant
73 :const:`subprocess.PIPE` (the default). By default a new pipe will be
74 created and connected.
75
76 * *stderr*: Either a file-like object representing the pipe to be connected
77 to the subprocess's standard error stream using
78 :meth:`~BaseEventLoop.connect_read_pipe`, or one of the constants
79 :const:`subprocess.PIPE` (the default) or :const:`subprocess.STDOUT`.
80 By default a new pipe will be created and connected. When
81 :const:`subprocess.STDOUT` is specified, the subprocess's standard error
82 stream will be connected to the same pipe as the standard output stream.
83
84 * All other keyword arguments are passed to :class:`subprocess.Popen`
85 without interpretation, except for *bufsize*, *universal_newlines* and
86 *shell*, which should not be specified at all.
87
88 Returns a pair of ``(transport, protocol)``, where *transport* is an
89 instance of :class:`BaseSubprocessTransport`.
90
91 This method is a :ref:`coroutine <coroutine>`.
92
93 See the constructor of the :class:`subprocess.Popen` class for parameters.
94
95.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
96
97 Create a subprocess from *cmd*, which is a string using the platform's
98 "shell" syntax. This is similar to the standard library
99 :class:`subprocess.Popen` class called with ``shell=True``.
100
101 See :meth:`~BaseEventLoop.subprocess_exec` for more details about
102 the remaining arguments.
103
104 Returns a pair of ``(transport, protocol)``, where *transport* is an
105 instance of :class:`BaseSubprocessTransport`.
106
107 This method is a :ref:`coroutine <coroutine>`.
108
109 See the constructor of the :class:`subprocess.Popen` class for parameters.
110
Victor Stinner08444382014-02-02 22:43:39 +0100111.. seealso::
112
Victor Stinner984600f2014-03-25 09:40:26 +0100113 The :meth:`BaseEventLoop.connect_read_pipe` and
114 :meth:`BaseEventLoop.connect_write_pipe` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100115
116
117Constants
118---------
119
120.. data:: asyncio.subprocess.PIPE
121
122 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
123 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
124 indicates that a pipe to the standard stream should be opened.
125
126.. data:: asyncio.subprocess.STDOUT
127
128 Special value that can be used as the *stderr* argument to
129 :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
130 indicates that standard error should go into the same handle as standard
131 output.
132
133.. data:: asyncio.subprocess.DEVNULL
134
Victor Stinner72804862014-03-21 11:44:49 +0100135 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
136 to :func:`create_subprocess_shell` and :func:`create_subprocess_exec` and
137 indicates that the special file :data:`os.devnull` will be used.
Victor Stinner08444382014-02-02 22:43:39 +0100138
139
140Process
141-------
142
143.. class:: asyncio.subprocess.Process
144
Victor Stinnerb79eb052014-02-03 23:08:14 +0100145 .. attribute:: pid
146
147 The identifier of the process.
148
149 Note that if you set the *shell* argument to ``True``, this is the
150 process identifier of the spawned shell.
151
152 .. attribute:: returncode
153
154 Return code of the process when it exited. A ``None`` value indicates
155 that the process has not terminated yet.
156
157 A negative value ``-N`` indicates that the child was terminated by signal
158 ``N`` (Unix only).
159
Victor Stinner08444382014-02-02 22:43:39 +0100160 .. attribute:: stdin
161
162 Standard input stream (write), ``None`` if the process was created with
163 ``stdin=None``.
164
165 .. attribute:: stdout
166
167 Standard output stream (read), ``None`` if the process was created with
168 ``stdout=None``.
169
170 .. attribute:: stderr
171
172 Standard error stream (read), ``None`` if the process was created with
173 ``stderr=None``.
174
Victor Stinner08444382014-02-02 22:43:39 +0100175 .. method:: communicate(input=None)
176
177 Interact with process: Send data to stdin. Read data from stdout and
178 stderr, until end-of-file is reached. Wait for process to terminate.
179 The optional *input* argument should be data to be sent to the child
180 process, or ``None``, if no data should be sent to the child. The type
181 of *input* must be bytes.
182
183 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
184
185 Note that if you want to send data to the process's stdin, you need to
Victor Stinner0c3949c2014-02-09 02:51:40 +0100186 create the Process object with ``stdin=PIPE``. Similarly, to get anything
Victor Stinner08444382014-02-02 22:43:39 +0100187 other than ``None`` in the result tuple, you need to give ``stdout=PIPE``
188 and/or ``stderr=PIPE`` too.
189
190 .. note::
191
192 The data read is buffered in memory, so do not use this method if the
193 data size is large or unlimited.
194
Victor Stinner7bdf7862014-03-16 21:29:31 +0100195 This method is a :ref:`coroutine <coroutine>`.
196
Victor Stinner08444382014-02-02 22:43:39 +0100197 .. method:: kill()
198
199 Kills the child. On Posix OSs the function sends :py:data:`SIGKILL` to
200 the child. On Windows :meth:`kill` is an alias for :meth:`terminate`.
201
Brian Curtina1afeec2014-02-08 18:36:14 -0600202 .. method:: send_signal(signal)
Victor Stinner08444382014-02-02 22:43:39 +0100203
204 Sends the signal *signal* to the child process.
205
206 .. note::
207
208 On Windows, :py:data:`SIGTERM` is an alias for :meth:`terminate`.
209 ``CTRL_C_EVENT`` and ``CTRL_BREAK_EVENT`` can be sent to processes
210 started with a *creationflags* parameter which includes
211 ``CREATE_NEW_PROCESS_GROUP``.
212
213 .. method:: terminate()
214
215 Stop the child. On Posix OSs the method sends :py:data:`signal.SIGTERM`
216 to the child. On Windows the Win32 API function
217 :c:func:`TerminateProcess` is called to stop the child.
218
Victor Stinner7bdf7862014-03-16 21:29:31 +0100219 .. method:: wait():
Victor Stinner08444382014-02-02 22:43:39 +0100220
221 Wait for child process to terminate. Set and return :attr:`returncode`
222 attribute.
223
Victor Stinner7bdf7862014-03-16 21:29:31 +0100224 This method is a :ref:`coroutine <coroutine>`.
225
Victor Stinnere48d4db2014-02-03 23:26:28 +0100226
227Example
228-------
229
230Implement a function similar to :func:`subprocess.getstatusoutput`, except that
231it does not use a shell. Get the output of the "python -m platform" command and
232display the output::
233
234 import asyncio
Victor Stinner6bc23962014-03-21 11:56:40 +0100235 import os
Victor Stinnere48d4db2014-02-03 23:26:28 +0100236 import sys
237 from asyncio import subprocess
238
239 @asyncio.coroutine
240 def getstatusoutput(*args):
241 proc = yield from asyncio.create_subprocess_exec(
242 *args,
243 stdout=subprocess.PIPE,
244 stderr=subprocess.STDOUT)
245 try:
246 stdout, _ = yield from proc.communicate()
247 except:
248 proc.kill()
249 yield from proc.wait()
250 raise
251 exitcode = yield from proc.wait()
252 return (exitcode, stdout)
253
Victor Stinner6bc23962014-03-21 11:56:40 +0100254 if os.name == 'nt':
255 loop = asyncio.ProactorEventLoop()
256 asyncio.set_event_loop(loop)
257 else:
258 loop = asyncio.get_event_loop()
Victor Stinnere48d4db2014-02-03 23:26:28 +0100259 coro = getstatusoutput(sys.executable, '-m', 'platform')
260 exitcode, stdout = loop.run_until_complete(coro)
261 if not exitcode:
262 stdout = stdout.decode('ascii').rstrip()
263 print("Platform: %s" % stdout)
264 else:
265 print("Python failed with exit code %s:" % exitcode)
266 sys.stdout.flush()
267 sys.stdout.buffer.flush()
268 sys.stdout.buffer.write(stdout)
269 sys.stdout.buffer.flush()
270 loop.close()