R David Murray | 6a14381 | 2013-12-20 14:37:39 -0500 | [diff] [blame] | 1 | .. currentmodule:: asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 2 | |
| 3 | Tasks and coroutines |
| 4 | ==================== |
| 5 | |
| 6 | .. _coroutine: |
| 7 | |
| 8 | Coroutines |
| 9 | ---------- |
| 10 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 11 | Coroutines used with :mod:`asyncio` may be implemented using the |
| 12 | :keyword:`async def` statement, or by using :term:`generators <generator>`. |
| 13 | The :keyword:`async def` type of coroutine was added in Python 3.5, and |
| 14 | is recommended if there is no need to support older Python versions. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 15 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 16 | Generator-based coroutines should be decorated with :func:`@asyncio.coroutine |
| 17 | <asyncio.coroutine>`, although this is not strictly enforced. |
| 18 | The decorator enables compatibility with :keyword:`async def` coroutines, |
| 19 | and also serves as documentation. Generator-based |
| 20 | coroutines use the ``yield from`` syntax introduced in :pep:`380`, |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 21 | instead of the original ``yield`` syntax. |
| 22 | |
| 23 | The word "coroutine", like the word "generator", is used for two |
| 24 | different (though related) concepts: |
| 25 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 26 | - The function that defines a coroutine |
| 27 | (a function definition using :keyword:`async def` or |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 28 | decorated with ``@asyncio.coroutine``). If disambiguation is needed |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 29 | we will call this a *coroutine function* (:func:`iscoroutinefunction` |
| 30 | returns ``True``). |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 31 | |
| 32 | - The object obtained by calling a coroutine function. This object |
| 33 | represents a computation or an I/O operation (usually a combination) |
| 34 | that will complete eventually. If disambiguation is needed we will |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 35 | call it a *coroutine object* (:func:`iscoroutine` returns ``True``). |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 36 | |
| 37 | Things a coroutine can do: |
| 38 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 39 | - ``result = await future`` or ``result = yield from future`` -- |
| 40 | suspends the coroutine until the |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 41 | future is done, then returns the future's result, or raises an |
| 42 | exception, which will be propagated. (If the future is cancelled, |
| 43 | it will raise a ``CancelledError`` exception.) Note that tasks are |
| 44 | futures, and everything said about futures also applies to tasks. |
| 45 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 46 | - ``result = await coroutine`` or ``result = yield from coroutine`` -- |
| 47 | wait for another coroutine to |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 48 | produce a result (or raise an exception, which will be propagated). |
| 49 | The ``coroutine`` expression must be a *call* to another coroutine. |
| 50 | |
| 51 | - ``return expression`` -- produce a result to the coroutine that is |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 52 | waiting for this one using :keyword:`await` or ``yield from``. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 53 | |
| 54 | - ``raise exception`` -- raise an exception in the coroutine that is |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 55 | waiting for this one using :keyword:`await` or ``yield from``. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 56 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 57 | Calling a coroutine does not start its code running -- |
| 58 | the coroutine object returned by the call doesn't do anything until you |
| 59 | schedule its execution. There are two basic ways to start it running: |
| 60 | call ``await coroutine`` or ``yield from coroutine`` from another coroutine |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 61 | (assuming the other coroutine is already running!), or schedule its execution |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 62 | using the :func:`ensure_future` function or the :meth:`AbstractEventLoop.create_task` |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 63 | method. |
| 64 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 65 | |
| 66 | Coroutines (and tasks) can only run when the event loop is running. |
| 67 | |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 68 | .. decorator:: coroutine |
| 69 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 70 | Decorator to mark generator-based coroutines. This enables |
| 71 | the generator use :keyword:`!yield from` to call :keyword:`async |
| 72 | def` coroutines, and also enables the generator to be called by |
| 73 | :keyword:`async def` coroutines, for instance using an |
| 74 | :keyword:`await` expression. |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 75 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 76 | There is no need to decorate :keyword:`async def` coroutines themselves. |
| 77 | |
| 78 | If the generator is not yielded from before it is destroyed, an error |
Victor Stinner | db39a0d | 2014-01-16 18:58:01 +0100 | [diff] [blame] | 79 | message is logged. See :ref:`Detect coroutines never scheduled |
| 80 | <asyncio-coroutine-not-scheduled>`. |
| 81 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 82 | .. note:: |
| 83 | |
| 84 | In this documentation, some methods are documented as coroutines, |
| 85 | even if they are plain Python functions returning a :class:`Future`. |
| 86 | This is intentional to have a freedom of tweaking the implementation |
| 87 | of these functions in the future. If such a function is needed to be |
Yury Selivanov | 04356e1 | 2015-06-30 22:13:22 -0400 | [diff] [blame] | 88 | used in a callback-style code, wrap its result with :func:`ensure_future`. |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 89 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 90 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 91 | .. _asyncio-hello-world-coroutine: |
| 92 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 93 | Example: Hello World coroutine |
| 94 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 95 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 96 | Example of coroutine displaying ``"Hello World"``:: |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 97 | |
| 98 | import asyncio |
| 99 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 100 | async def hello_world(): |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 101 | print("Hello World!") |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 102 | |
| 103 | loop = asyncio.get_event_loop() |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 104 | # Blocking call which returns when the hello_world() coroutine is done |
| 105 | loop.run_until_complete(hello_world()) |
| 106 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 107 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 108 | .. seealso:: |
| 109 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 110 | The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>` |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 111 | example uses the :meth:`AbstractEventLoop.call_soon` method to schedule a |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 112 | callback. |
| 113 | |
| 114 | |
| 115 | .. _asyncio-date-coroutine: |
| 116 | |
| 117 | Example: Coroutine displaying the current date |
| 118 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 119 | |
| 120 | Example of coroutine displaying the current date every second during 5 seconds |
| 121 | using the :meth:`sleep` function:: |
| 122 | |
| 123 | import asyncio |
| 124 | import datetime |
| 125 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 126 | async def display_date(loop): |
| 127 | end_time = loop.time() + 5.0 |
| 128 | while True: |
| 129 | print(datetime.datetime.now()) |
| 130 | if (loop.time() + 1.0) >= end_time: |
| 131 | break |
| 132 | await asyncio.sleep(1) |
| 133 | |
| 134 | loop = asyncio.get_event_loop() |
| 135 | # Blocking call which returns when the display_date() coroutine is done |
| 136 | loop.run_until_complete(display_date(loop)) |
| 137 | loop.close() |
| 138 | |
| 139 | The same coroutine implemented using a generator:: |
| 140 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 141 | @asyncio.coroutine |
| 142 | def display_date(loop): |
| 143 | end_time = loop.time() + 5.0 |
| 144 | while True: |
| 145 | print(datetime.datetime.now()) |
| 146 | if (loop.time() + 1.0) >= end_time: |
| 147 | break |
| 148 | yield from asyncio.sleep(1) |
| 149 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 150 | .. seealso:: |
| 151 | |
| 152 | The :ref:`display the current date with call_later() |
| 153 | <asyncio-date-callback>` example uses a callback with the |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 154 | :meth:`AbstractEventLoop.call_later` method. |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 155 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 156 | |
| 157 | Example: Chain coroutines |
| 158 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 159 | |
| 160 | Example chaining coroutines:: |
| 161 | |
| 162 | import asyncio |
| 163 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 164 | async def compute(x, y): |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 165 | print("Compute %s + %s ..." % (x, y)) |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 166 | await asyncio.sleep(1.0) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 167 | return x + y |
| 168 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 169 | async def print_sum(x, y): |
| 170 | result = await compute(x, y) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 171 | print("%s + %s = %s" % (x, y, result)) |
| 172 | |
| 173 | loop = asyncio.get_event_loop() |
| 174 | loop.run_until_complete(print_sum(1, 2)) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 175 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 176 | |
| 177 | ``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits |
Brian Curtin | a1afeec | 2014-02-08 18:36:14 -0600 | [diff] [blame] | 178 | until ``compute()`` is completed before returning its result. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 179 | |
Victor Stinner | 1c4b892 | 2013-12-12 12:35:17 +0100 | [diff] [blame] | 180 | Sequence diagram of the example: |
| 181 | |
| 182 | .. image:: tulip_coro.png |
| 183 | :align: center |
| 184 | |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 185 | The "Task" is created by the :meth:`AbstractEventLoop.run_until_complete` method |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 186 | when it gets a coroutine object instead of a task. |
Victor Stinner | 86e139a | 2013-12-13 12:51:24 +0100 | [diff] [blame] | 187 | |
| 188 | The diagram shows the control flow, it does not describe exactly how things |
| 189 | work internally. For example, the sleep coroutine creates an internal future |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 190 | which uses :meth:`AbstractEventLoop.call_later` to wake up the task in 1 second. |
Victor Stinner | 1c4b892 | 2013-12-12 12:35:17 +0100 | [diff] [blame] | 191 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 192 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 193 | InvalidStateError |
| 194 | ----------------- |
| 195 | |
| 196 | .. exception:: InvalidStateError |
| 197 | |
| 198 | The operation is not allowed in this state. |
| 199 | |
| 200 | |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 201 | TimeoutError |
| 202 | ------------ |
| 203 | |
| 204 | .. exception:: TimeoutError |
| 205 | |
| 206 | The operation exceeded the given deadline. |
| 207 | |
| 208 | .. note:: |
| 209 | |
| 210 | This exception is different from the builtin :exc:`TimeoutError` exception! |
| 211 | |
| 212 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 213 | Future |
| 214 | ------ |
| 215 | |
| 216 | .. class:: Future(\*, loop=None) |
| 217 | |
| 218 | This class is *almost* compatible with :class:`concurrent.futures.Future`. |
| 219 | |
| 220 | Differences: |
| 221 | |
| 222 | - :meth:`result` and :meth:`exception` do not take a timeout argument and |
| 223 | raise an exception when the future isn't done yet. |
| 224 | |
| 225 | - Callbacks registered with :meth:`add_done_callback` are always called |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 226 | via the event loop's :meth:`~AbstractEventLoop.call_soon_threadsafe`. |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 227 | |
| 228 | - This class is not compatible with the :func:`~concurrent.futures.wait` and |
| 229 | :func:`~concurrent.futures.as_completed` functions in the |
| 230 | :mod:`concurrent.futures` package. |
| 231 | |
Victor Stinner | 8370496 | 2015-02-25 14:24:15 +0100 | [diff] [blame] | 232 | This class is :ref:`not thread safe <asyncio-multithreading>`. |
| 233 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 234 | .. method:: cancel() |
| 235 | |
| 236 | Cancel the future and schedule callbacks. |
| 237 | |
| 238 | If the future is already done or cancelled, return ``False``. Otherwise, |
| 239 | change the future's state to cancelled, schedule the callbacks and return |
| 240 | ``True``. |
| 241 | |
| 242 | .. method:: cancelled() |
| 243 | |
| 244 | Return ``True`` if the future was cancelled. |
| 245 | |
| 246 | .. method:: done() |
| 247 | |
| 248 | Return True if the future is done. |
| 249 | |
| 250 | Done means either that a result / exception are available, or that the |
| 251 | future was cancelled. |
| 252 | |
| 253 | .. method:: result() |
| 254 | |
| 255 | Return the result this future represents. |
| 256 | |
| 257 | If the future has been cancelled, raises :exc:`CancelledError`. If the |
| 258 | future's result isn't yet available, raises :exc:`InvalidStateError`. If |
| 259 | the future is done and has an exception set, this exception is raised. |
| 260 | |
| 261 | .. method:: exception() |
| 262 | |
| 263 | Return the exception that was set on this future. |
| 264 | |
| 265 | The exception (or ``None`` if no exception was set) is returned only if |
| 266 | the future is done. If the future has been cancelled, raises |
| 267 | :exc:`CancelledError`. If the future isn't done yet, raises |
| 268 | :exc:`InvalidStateError`. |
| 269 | |
| 270 | .. method:: add_done_callback(fn) |
| 271 | |
| 272 | Add a callback to be run when the future becomes done. |
| 273 | |
| 274 | The callback is called with a single argument - the future object. If the |
| 275 | future is already done when this is called, the callback is scheduled |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 276 | with :meth:`~AbstractEventLoop.call_soon`. |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 277 | |
Victor Stinner | 8464c24 | 2014-11-28 13:15:41 +0100 | [diff] [blame] | 278 | :ref:`Use functools.partial to pass parameters to the callback |
| 279 | <asyncio-pass-keywords>`. For example, |
| 280 | ``fut.add_done_callback(functools.partial(print, "Future:", |
| 281 | flush=True))`` will call ``print("Future:", fut, flush=True)``. |
| 282 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 283 | .. method:: remove_done_callback(fn) |
| 284 | |
| 285 | Remove all instances of a callback from the "call when done" list. |
| 286 | |
| 287 | Returns the number of callbacks removed. |
| 288 | |
| 289 | .. method:: set_result(result) |
| 290 | |
| 291 | Mark the future done and set its result. |
| 292 | |
| 293 | If the future is already done when this method is called, raises |
| 294 | :exc:`InvalidStateError`. |
| 295 | |
| 296 | .. method:: set_exception(exception) |
| 297 | |
| 298 | Mark the future done and set an exception. |
| 299 | |
| 300 | If the future is already done when this method is called, raises |
| 301 | :exc:`InvalidStateError`. |
| 302 | |
| 303 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 304 | Example: Future with run_until_complete() |
| 305 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 306 | |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 307 | Example combining a :class:`Future` and a :ref:`coroutine function |
| 308 | <coroutine>`:: |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 309 | |
| 310 | import asyncio |
| 311 | |
| 312 | @asyncio.coroutine |
| 313 | def slow_operation(future): |
| 314 | yield from asyncio.sleep(1) |
Victor Stinner | 04e05da | 2014-02-17 10:54:30 +0100 | [diff] [blame] | 315 | future.set_result('Future is done!') |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 316 | |
| 317 | loop = asyncio.get_event_loop() |
| 318 | future = asyncio.Future() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 319 | asyncio.ensure_future(slow_operation(future)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 320 | loop.run_until_complete(future) |
| 321 | print(future.result()) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 322 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 323 | |
Terry Jan Reedy | c935a95 | 2014-07-24 02:33:14 -0400 | [diff] [blame] | 324 | The coroutine function is responsible for the computation (which takes 1 second) |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 325 | and it stores the result into the future. The |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 326 | :meth:`~AbstractEventLoop.run_until_complete` method waits for the completion of |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 327 | the future. |
| 328 | |
| 329 | .. note:: |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 330 | The :meth:`~AbstractEventLoop.run_until_complete` method uses internally the |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 331 | :meth:`~Future.add_done_callback` method to be notified when the future is |
| 332 | done. |
| 333 | |
| 334 | |
| 335 | Example: Future with run_forever() |
| 336 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 337 | |
| 338 | The previous example can be written differently using the |
| 339 | :meth:`Future.add_done_callback` method to describe explicitly the control |
| 340 | flow:: |
| 341 | |
| 342 | import asyncio |
| 343 | |
| 344 | @asyncio.coroutine |
| 345 | def slow_operation(future): |
| 346 | yield from asyncio.sleep(1) |
Victor Stinner | 04e05da | 2014-02-17 10:54:30 +0100 | [diff] [blame] | 347 | future.set_result('Future is done!') |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 348 | |
| 349 | def got_result(future): |
| 350 | print(future.result()) |
| 351 | loop.stop() |
| 352 | |
| 353 | loop = asyncio.get_event_loop() |
| 354 | future = asyncio.Future() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 355 | asyncio.ensure_future(slow_operation(future)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 356 | future.add_done_callback(got_result) |
Victor Stinner | 04e05da | 2014-02-17 10:54:30 +0100 | [diff] [blame] | 357 | try: |
| 358 | loop.run_forever() |
| 359 | finally: |
| 360 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 361 | |
Victor Stinner | 039f703 | 2014-12-02 17:52:45 +0100 | [diff] [blame] | 362 | In this example, the future is used to link ``slow_operation()`` to |
| 363 | ``got_result()``: when ``slow_operation()`` is done, ``got_result()`` is called |
| 364 | with the result. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 365 | |
| 366 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 367 | Task |
| 368 | ---- |
| 369 | |
| 370 | .. class:: Task(coro, \*, loop=None) |
| 371 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 372 | Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a |
| 373 | future. A task is a subclass of :class:`Future`. |
| 374 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 375 | A task is responsible for executing a coroutine object in an event loop. If |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 376 | the wrapped coroutine yields from a future, the task suspends the execution |
| 377 | of the wrapped coroutine and waits for the completition of the future. When |
| 378 | the future is done, the execution of the wrapped coroutine restarts with the |
| 379 | result or the exception of the future. |
| 380 | |
| 381 | Event loops use cooperative scheduling: an event loop only runs one task at |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 382 | a time. Other tasks may run in parallel if other event loops are |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 383 | running in different threads. While a task waits for the completion of a |
| 384 | future, the event loop executes a new task. |
| 385 | |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 386 | The cancellation of a task is different from the cancelation of a |
| 387 | future. Calling :meth:`cancel` will throw a |
| 388 | :exc:`~concurrent.futures.CancelledError` to the wrapped |
| 389 | coroutine. :meth:`~Future.cancelled` only returns ``True`` if the |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 390 | wrapped coroutine did not catch the |
| 391 | :exc:`~concurrent.futures.CancelledError` exception, or raised a |
| 392 | :exc:`~concurrent.futures.CancelledError` exception. |
| 393 | |
| 394 | If a pending task is destroyed, the execution of its wrapped :ref:`coroutine |
| 395 | <coroutine>` did not complete. It is probably a bug and a warning is |
| 396 | logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`. |
| 397 | |
Yury Selivanov | 04356e1 | 2015-06-30 22:13:22 -0400 | [diff] [blame] | 398 | Don't directly create :class:`Task` instances: use the :func:`ensure_future` |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 399 | function or the :meth:`AbstractEventLoop.create_task` method. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 400 | |
Victor Stinner | 8370496 | 2015-02-25 14:24:15 +0100 | [diff] [blame] | 401 | This class is :ref:`not thread safe <asyncio-multithreading>`. |
| 402 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 403 | .. classmethod:: all_tasks(loop=None) |
| 404 | |
| 405 | Return a set of all tasks for an event loop. |
| 406 | |
| 407 | By default all tasks for the current event loop are returned. |
| 408 | |
Victor Stinner | 742520b | 2013-12-10 12:14:50 +0100 | [diff] [blame] | 409 | .. classmethod:: current_task(loop=None) |
| 410 | |
| 411 | Return the currently running task in an event loop or ``None``. |
| 412 | |
| 413 | By default the current task for the current event loop is returned. |
| 414 | |
| 415 | ``None`` is returned when called not in the context of a :class:`Task`. |
| 416 | |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 417 | .. method:: cancel() |
| 418 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 419 | Request that this task cancel itself. |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 420 | |
| 421 | This arranges for a :exc:`~concurrent.futures.CancelledError` to be |
| 422 | thrown into the wrapped coroutine on the next cycle through the event |
| 423 | loop. The coroutine then has a chance to clean up or even deny the |
| 424 | request using try/except/finally. |
| 425 | |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 426 | Unlike :meth:`Future.cancel`, this does not guarantee that the task |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 427 | will be cancelled: the exception might be caught and acted upon, delaying |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 428 | cancellation of the task or preventing cancellation completely. The task |
| 429 | may also return a value or raise a different exception. |
Victor Stinner | 8d21357 | 2014-06-02 23:06:46 +0200 | [diff] [blame] | 430 | |
| 431 | Immediately after this method is called, :meth:`~Future.cancelled` will |
| 432 | not return ``True`` (unless the task was already cancelled). A task will |
| 433 | be marked as cancelled when the wrapped coroutine terminates with a |
| 434 | :exc:`~concurrent.futures.CancelledError` exception (even if |
| 435 | :meth:`cancel` was not called). |
| 436 | |
| 437 | .. method:: get_stack(\*, limit=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 438 | |
| 439 | Return the list of stack frames for this task's coroutine. |
| 440 | |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 441 | If the coroutine is not done, this returns the stack where it is |
| 442 | suspended. If the coroutine has completed successfully or was |
| 443 | cancelled, this returns an empty list. If the coroutine was |
| 444 | terminated by an exception, this returns the list of traceback |
| 445 | frames. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 446 | |
| 447 | The frames are always ordered from oldest to newest. |
| 448 | |
Brian Curtin | a1afeec | 2014-02-08 18:36:14 -0600 | [diff] [blame] | 449 | The optional limit gives the maximum number of frames to return; by |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 450 | default all available frames are returned. Its meaning differs depending |
| 451 | on whether a stack or a traceback is returned: the newest frames of a |
| 452 | stack are returned, but the oldest frames of a traceback are returned. |
| 453 | (This matches the behavior of the traceback module.) |
| 454 | |
| 455 | For reasons beyond our control, only one stack frame is returned for a |
| 456 | suspended coroutine. |
| 457 | |
| 458 | .. method:: print_stack(\*, limit=None, file=None) |
| 459 | |
| 460 | Print the stack or traceback for this task's coroutine. |
| 461 | |
| 462 | This produces output similar to that of the traceback module, for the |
| 463 | frames retrieved by get_stack(). The limit argument is passed to |
| 464 | get_stack(). The file argument is an I/O stream to which the output |
R David Murray | 22dd833 | 2014-09-24 11:09:09 -0400 | [diff] [blame] | 465 | is written; by default output is written to sys.stderr. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 466 | |
| 467 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 468 | Example: Parallel execution of tasks |
| 469 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 470 | |
| 471 | Example executing 3 tasks (A, B, C) in parallel:: |
| 472 | |
| 473 | import asyncio |
| 474 | |
| 475 | @asyncio.coroutine |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 476 | def factorial(name, number): |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 477 | f = 1 |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 478 | for i in range(2, number+1): |
| 479 | print("Task %s: Compute factorial(%s)..." % (name, i)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 480 | yield from asyncio.sleep(1) |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 481 | f *= i |
| 482 | print("Task %s: factorial(%s) = %s" % (name, number, f)) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 483 | |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 484 | loop = asyncio.get_event_loop() |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 485 | tasks = [ |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 486 | asyncio.ensure_future(factorial("A", 2)), |
| 487 | asyncio.ensure_future(factorial("B", 3)), |
| 488 | asyncio.ensure_future(factorial("C", 4))] |
Andrew Svetlov | 4365b83 | 2016-08-08 03:10:39 +0300 | [diff] [blame] | 489 | loop.run_until_complete(asyncio.gather(*tasks)) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 490 | loop.close() |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 491 | |
| 492 | Output:: |
| 493 | |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 494 | Task A: Compute factorial(2)... |
| 495 | Task B: Compute factorial(2)... |
| 496 | Task C: Compute factorial(2)... |
| 497 | Task A: factorial(2) = 2 |
| 498 | Task B: Compute factorial(3)... |
| 499 | Task C: Compute factorial(3)... |
| 500 | Task B: factorial(3) = 6 |
| 501 | Task C: Compute factorial(4)... |
| 502 | Task C: factorial(4) = 24 |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 503 | |
Victor Stinner | 34f2946 | 2013-12-10 02:51:05 +0100 | [diff] [blame] | 504 | A task is automatically scheduled for execution when it is created. The event |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 505 | loop stops when all tasks are done. |
| 506 | |
| 507 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 508 | Task functions |
| 509 | -------------- |
| 510 | |
Eli Bendersky | 029981b | 2014-01-20 07:02:22 -0800 | [diff] [blame] | 511 | .. note:: |
| 512 | |
Martin Panter | c04fb56 | 2016-02-10 05:44:01 +0000 | [diff] [blame] | 513 | In the functions below, the optional *loop* argument allows explicitly setting |
Eli Bendersky | 029981b | 2014-01-20 07:02:22 -0800 | [diff] [blame] | 514 | the event loop object used by the underlying task or coroutine. If it's |
| 515 | not provided, the default event loop is used. |
| 516 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 517 | .. function:: as_completed(fs, \*, loop=None, timeout=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 518 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 519 | Return an iterator whose values, when waited for, are :class:`Future` |
| 520 | instances. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 521 | |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 522 | Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures |
| 523 | are done. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 524 | |
| 525 | Example:: |
| 526 | |
| 527 | for f in as_completed(fs): |
| 528 | result = yield from f # The 'yield from' may raise |
| 529 | # Use result |
| 530 | |
| 531 | .. note:: |
| 532 | |
| 533 | The futures ``f`` are not necessarily members of fs. |
| 534 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 535 | .. function:: ensure_future(coro_or_future, \*, loop=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 536 | |
Victor Stinner | 980dd84 | 2014-10-12 21:36:17 +0200 | [diff] [blame] | 537 | Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in |
| 538 | a future. Return a :class:`Task` object. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 539 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 540 | If the argument is a :class:`Future`, it is returned directly. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 541 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 542 | .. versionadded:: 3.4.4 |
| 543 | |
Yury Selivanov | e319ab0 | 2015-12-15 00:45:24 -0500 | [diff] [blame] | 544 | .. versionchanged:: 3.5.1 |
| 545 | The function accepts any :term:`awaitable` object. |
| 546 | |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 547 | .. seealso:: |
| 548 | |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 549 | The :meth:`AbstractEventLoop.create_task` method. |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 550 | |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 551 | .. function:: async(coro_or_future, \*, loop=None) |
| 552 | |
| 553 | A deprecated alias to :func:`ensure_future`. |
| 554 | |
| 555 | .. deprecated:: 3.4.4 |
| 556 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 557 | .. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 558 | |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 559 | Return a future aggregating results from the given coroutine objects or |
| 560 | futures. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 561 | |
| 562 | All futures must share the same event loop. If all the tasks are done |
| 563 | successfully, the returned future's result is the list of results (in the |
| 564 | order of the original sequence, not necessarily the order of results |
Victor Stinner | 12c68b2 | 2014-02-09 01:35:24 +0100 | [diff] [blame] | 565 | arrival). If *return_exceptions* is True, exceptions in the tasks are |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 566 | treated the same as successful results, and gathered in the result list; |
| 567 | otherwise, the first raised exception will be immediately propagated to the |
| 568 | returned future. |
| 569 | |
| 570 | Cancellation: if the outer Future is cancelled, all children (that have not |
| 571 | completed yet) are also cancelled. If any child is cancelled, this is |
| 572 | treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the |
| 573 | outer Future is *not* cancelled in this case. (This is to prevent the |
| 574 | cancellation of one child to cause other children to be cancelled.) |
| 575 | |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 576 | .. function:: iscoroutine(obj) |
| 577 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 578 | Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`, |
| 579 | which may be based on a generator or an :keyword:`async def` coroutine. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 580 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 581 | .. function:: iscoroutinefunction(func) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 582 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 583 | Return ``True`` if *func* is determined to be a :ref:`coroutine function |
| 584 | <coroutine>`, which may be a decorated generator function or an |
| 585 | :keyword:`async def` function. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 586 | |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 587 | .. function:: run_coroutine_threadsafe(coro, loop) |
| 588 | |
| 589 | Submit a :ref:`coroutine object <coroutine>` to a given event loop. |
| 590 | |
| 591 | Return a :class:`concurrent.futures.Future` to access the result. |
| 592 | |
| 593 | This function is meant to be called from a different thread than the one |
| 594 | where the event loop is running. Usage:: |
| 595 | |
| 596 | # Create a coroutine |
| 597 | coro = asyncio.sleep(1, result=3) |
| 598 | # Submit the coroutine to a given loop |
| 599 | future = asyncio.run_coroutine_threadsafe(coro, loop) |
| 600 | # Wait for the result with an optional timeout argument |
| 601 | assert future.result(timeout) == 3 |
| 602 | |
| 603 | If an exception is raised in the coroutine, the returned future will be |
| 604 | notified. It can also be used to cancel the task in the event loop:: |
| 605 | |
| 606 | try: |
| 607 | result = future.result(timeout) |
| 608 | except asyncio.TimeoutError: |
| 609 | print('The coroutine took too long, cancelling the task...') |
| 610 | future.cancel() |
| 611 | except Exception as exc: |
| 612 | print('The coroutine raised an exception: {!r}'.format(exc)) |
| 613 | else: |
| 614 | print('The coroutine returned: {!r}'.format(result)) |
| 615 | |
| 616 | See the :ref:`concurrency and multithreading <asyncio-multithreading>` |
| 617 | section of the documentation. |
| 618 | |
| 619 | .. note:: |
| 620 | |
Andrew Svetlov | 3af81f2 | 2016-01-11 14:45:25 +0200 | [diff] [blame] | 621 | Unlike other functions from the module, |
| 622 | :func:`run_coroutine_threadsafe` requires the *loop* argument to |
Zachary Ware | f9aff92 | 2016-06-01 00:01:10 -0500 | [diff] [blame] | 623 | be passed explicitly. |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 624 | |
Andrew Svetlov | ea47134 | 2016-01-11 15:41:43 +0200 | [diff] [blame] | 625 | .. versionadded:: 3.5.1 |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 626 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 627 | .. coroutinefunction:: sleep(delay, result=None, \*, loop=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 628 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 629 | Create a :ref:`coroutine <coroutine>` that completes after a given |
Eli Bendersky | 2d26af8 | 2014-01-20 06:59:23 -0800 | [diff] [blame] | 630 | time (in seconds). If *result* is provided, it is produced to the caller |
| 631 | when the coroutine completes. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 632 | |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 633 | The resolution of the sleep depends on the :ref:`granularity of the event |
| 634 | loop <asyncio-delayed-calls>`. |
| 635 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 636 | This function is a :ref:`coroutine <coroutine>`. |
| 637 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 638 | .. function:: shield(arg, \*, loop=None) |
| 639 | |
| 640 | Wait for a future, shielding it from cancellation. |
| 641 | |
| 642 | The statement:: |
| 643 | |
| 644 | res = yield from shield(something()) |
| 645 | |
| 646 | is exactly equivalent to the statement:: |
| 647 | |
| 648 | res = yield from something() |
| 649 | |
| 650 | *except* that if the coroutine containing it is cancelled, the task running |
| 651 | in ``something()`` is not cancelled. From the point of view of |
| 652 | ``something()``, the cancellation did not happen. But its caller is still |
| 653 | cancelled, so the yield-from expression still raises |
| 654 | :exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is |
| 655 | cancelled by other means this will still cancel ``shield()``. |
| 656 | |
| 657 | If you want to completely ignore cancellation (not recommended) you can |
| 658 | combine ``shield()`` with a try/except clause, as follows:: |
| 659 | |
| 660 | try: |
| 661 | res = yield from shield(something()) |
| 662 | except CancelledError: |
| 663 | res = None |
| 664 | |
Yury Selivanov | 950204d | 2016-05-16 16:23:00 -0400 | [diff] [blame] | 665 | |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 666 | .. coroutinefunction:: wait(futures, \*, loop=None, timeout=None,\ |
| 667 | return_when=ALL_COMPLETED) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 668 | |
Victor Stinner | 59759ff | 2014-01-16 19:30:21 +0100 | [diff] [blame] | 669 | Wait for the Futures and coroutine objects given by the sequence *futures* |
| 670 | to complete. Coroutines will be wrapped in Tasks. Returns two sets of |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame] | 671 | :class:`Future`: (done, pending). |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 672 | |
Victor Stinner | db74d98 | 2014-06-10 11:16:05 +0200 | [diff] [blame] | 673 | The sequence *futures* must not be empty. |
| 674 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 675 | *timeout* can be used to control the maximum number of seconds to wait before |
| 676 | returning. *timeout* can be an int or float. If *timeout* is not specified |
| 677 | or ``None``, there is no limit to the wait time. |
| 678 | |
| 679 | *return_when* indicates when this function should return. It must be one of |
Victor Stinner | 933a8c8 | 2013-12-03 01:59:38 +0100 | [diff] [blame] | 680 | the following constants of the :mod:`concurrent.futures` module: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 681 | |
| 682 | .. tabularcolumns:: |l|L| |
| 683 | |
| 684 | +-----------------------------+----------------------------------------+ |
| 685 | | Constant | Description | |
| 686 | +=============================+========================================+ |
| 687 | | :const:`FIRST_COMPLETED` | The function will return when any | |
| 688 | | | future finishes or is cancelled. | |
| 689 | +-----------------------------+----------------------------------------+ |
| 690 | | :const:`FIRST_EXCEPTION` | The function will return when any | |
| 691 | | | future finishes by raising an | |
| 692 | | | exception. If no future raises an | |
| 693 | | | exception then it is equivalent to | |
| 694 | | | :const:`ALL_COMPLETED`. | |
| 695 | +-----------------------------+----------------------------------------+ |
| 696 | | :const:`ALL_COMPLETED` | The function will return when all | |
| 697 | | | futures finish or are cancelled. | |
| 698 | +-----------------------------+----------------------------------------+ |
| 699 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 700 | This function is a :ref:`coroutine <coroutine>`. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 701 | |
| 702 | Usage:: |
| 703 | |
| 704 | done, pending = yield from asyncio.wait(fs) |
| 705 | |
| 706 | .. note:: |
| 707 | |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 708 | This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done |
| 709 | when the timeout occurs are returned in the second set. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 710 | |
Victor Stinner | 3e09e32 | 2013-12-03 01:22:06 +0100 | [diff] [blame] | 711 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 712 | .. coroutinefunction:: wait_for(fut, timeout, \*, loop=None) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 713 | |
| 714 | Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>` |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 715 | to complete with timeout. If *timeout* is ``None``, block until the future |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 716 | completes. |
| 717 | |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 718 | Coroutine will be wrapped in :class:`Task`. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 719 | |
| 720 | Returns result of the Future or coroutine. When a timeout occurs, it |
Victor Stinner | 28d0ae48 | 2014-05-29 00:04:57 +0200 | [diff] [blame] | 721 | cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 722 | cancellation, wrap it in :func:`shield`. |
| 723 | |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 724 | If the wait is cancelled, the future *fut* is also cancelled. |
| 725 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 726 | This function is a :ref:`coroutine <coroutine>`, usage:: |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 727 | |
Victor Stinner | 530ef2f | 2014-07-08 12:39:10 +0200 | [diff] [blame] | 728 | result = yield from asyncio.wait_for(fut, 60.0) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 729 | |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 730 | .. versionchanged:: 3.4.3 |
| 731 | If the wait is cancelled, the future *fut* is now also cancelled. |