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 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 3 | |
| 4 | ==================== |
| 5 | Coroutines and Tasks |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 6 | ==================== |
| 7 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 8 | This section outlines high-level asyncio APIs to work with coroutines |
| 9 | and Tasks. |
lf | 627d2c8 | 2017-07-25 17:03:51 -0600 | [diff] [blame] | 10 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 11 | .. contents:: |
| 12 | :depth: 1 |
| 13 | :local: |
| 14 | |
lf | 627d2c8 | 2017-07-25 17:03:51 -0600 | [diff] [blame] | 15 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 16 | .. _coroutine: |
| 17 | |
| 18 | Coroutines |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 19 | ========== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 20 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 21 | Coroutines declared with async/await syntax is the preferred way of |
| 22 | writing asyncio applications. For example, the following snippet |
Yury Selivanov | b042cf1 | 2018-09-18 02:47:54 -0400 | [diff] [blame] | 23 | of code (requires Python 3.7+) prints "hello", waits 1 second, |
| 24 | and then prints "world":: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 25 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 26 | >>> import asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 27 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 28 | >>> async def main(): |
| 29 | ... print('hello') |
| 30 | ... await asyncio.sleep(1) |
| 31 | ... print('world') |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 32 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 33 | >>> asyncio.run(main()) |
| 34 | hello |
| 35 | world |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 36 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 37 | Note that simply calling a coroutine will not schedule it to |
| 38 | be executed:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 39 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 40 | >>> main() |
| 41 | <coroutine object main at 0x1053bb7c8> |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 42 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 43 | To actually run a coroutine asyncio provides three main mechanisms: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 44 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 45 | * The :func:`asyncio.run` function to run the top-level |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 46 | entry point "main()" function (see the above example.) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 47 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 48 | * Awaiting on a coroutine. The following snippet of code will |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 49 | print "hello" after waiting for 1 second, and then print "world" |
| 50 | after waiting for *another* 2 seconds:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 51 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 52 | import asyncio |
| 53 | import time |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 54 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 55 | async def say_after(delay, what): |
| 56 | await asyncio.sleep(delay) |
| 57 | print(what) |
| 58 | |
| 59 | async def main(): |
| 60 | print('started at', time.strftime('%X')) |
| 61 | |
| 62 | await say_after(1, 'hello') |
| 63 | await say_after(2, 'world') |
| 64 | |
| 65 | print('finished at', time.strftime('%X')) |
| 66 | |
| 67 | asyncio.run(main()) |
| 68 | |
| 69 | Expected output:: |
| 70 | |
| 71 | started at 17:13:52 |
| 72 | hello |
| 73 | world |
| 74 | finished at 17:13:55 |
| 75 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 76 | * The :func:`asyncio.create_task` function to run coroutines |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 77 | concurrently as asyncio :class:`Tasks <Task>`. |
| 78 | |
Danny Hermes | 7bfbda4 | 2018-09-17 21:49:21 -0700 | [diff] [blame] | 79 | Let's modify the above example and run two ``say_after`` coroutines |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 80 | *concurrently*:: |
| 81 | |
| 82 | async def main(): |
| 83 | task1 = asyncio.create_task( |
| 84 | say_after(1, 'hello')) |
| 85 | |
| 86 | task2 = asyncio.create_task( |
| 87 | say_after(2, 'world')) |
| 88 | |
| 89 | print('started at', time.strftime('%X')) |
| 90 | |
| 91 | # Wait until both tasks are completed (should take |
| 92 | # around 2 seconds.) |
| 93 | await task1 |
| 94 | await task2 |
| 95 | |
| 96 | print('finished at', time.strftime('%X')) |
| 97 | |
| 98 | Note that expected output now shows that the snippet runs |
| 99 | 1 second faster than before:: |
| 100 | |
| 101 | started at 17:14:32 |
| 102 | hello |
| 103 | world |
| 104 | finished at 17:14:34 |
| 105 | |
| 106 | Note that in this documentation the term "coroutine" can be used for |
| 107 | two closely related concepts: |
| 108 | |
| 109 | * a *coroutine function*: an :keyword:`async def` function; |
| 110 | |
| 111 | * a *coroutine object*: object returned by calling a |
| 112 | *coroutine function*. |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 113 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 114 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 115 | Running an asyncio Program |
| 116 | ========================== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 117 | |
Elvis Pranskevichus | 63536bd | 2018-05-19 23:15:06 -0400 | [diff] [blame] | 118 | .. function:: run(coro, \*, debug=False) |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 119 | |
| 120 | This function runs the passed coroutine, taking care of |
| 121 | managing the asyncio event loop and finalizing asynchronous |
| 122 | generators. |
| 123 | |
| 124 | This function cannot be called when another asyncio event loop is |
| 125 | running in the same thread. |
| 126 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 127 | If *debug* is ``True``, the event loop will be run in debug mode. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 128 | |
| 129 | This function always creates a new event loop and closes it at |
| 130 | the end. It should be used as a main entry point for asyncio |
| 131 | programs, and should ideally only be called once. |
| 132 | |
| 133 | .. versionadded:: 3.7 |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 134 | **Important:** this function has been added to asyncio in |
| 135 | Python 3.7 on a :term:`provisional basis <provisional api>`. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 136 | |
| 137 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 138 | Creating Tasks |
| 139 | ============== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 140 | |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 141 | .. function:: create_task(coro, \*, name=None) |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 142 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 143 | Wrap the *coro* :ref:`coroutine <coroutine>` into a task and schedule |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 144 | its execution. Return the task object. |
| 145 | |
| 146 | If *name* is not ``None``, it is set as the name of the task using |
| 147 | :meth:`Task.set_name`. |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 148 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 149 | The task is executed in the loop returned by :func:`get_running_loop`, |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 150 | :exc:`RuntimeError` is raised if there is no running loop in |
| 151 | current thread. |
| 152 | |
| 153 | .. versionadded:: 3.7 |
| 154 | |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 155 | .. versionchanged:: 3.8 |
| 156 | Added the ``name`` parameter. |
| 157 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 158 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 159 | Sleeping |
| 160 | ======== |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 161 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 162 | .. coroutinefunction:: sleep(delay, result=None, \*, loop=None) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 163 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 164 | Block for *delay* seconds. |
| 165 | |
| 166 | If *result* is provided, it is returned to the caller |
Eli Bendersky | 2d26af8 | 2014-01-20 06:59:23 -0800 | [diff] [blame] | 167 | when the coroutine completes. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 168 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 169 | .. _asyncio_example_sleep: |
Victor Stinner | 45b27ed | 2014-02-01 02:36:43 +0100 | [diff] [blame] | 170 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 171 | Example of coroutine displaying the current date every second |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 172 | for 5 seconds:: |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 173 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 174 | import asyncio |
| 175 | import datetime |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 176 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 177 | async def display_date(): |
| 178 | loop = asyncio.get_running_loop() |
| 179 | end_time = loop.time() + 5.0 |
| 180 | while True: |
| 181 | print(datetime.datetime.now()) |
| 182 | if (loop.time() + 1.0) >= end_time: |
| 183 | break |
| 184 | await asyncio.sleep(1) |
| 185 | |
| 186 | asyncio.run(display_date()) |
| 187 | |
| 188 | |
| 189 | Running Tasks Concurrently |
| 190 | ========================== |
| 191 | |
Yury Selivanov | 394374e | 2018-09-17 15:35:24 -0400 | [diff] [blame] | 192 | .. function:: gather(\*fs, loop=None, return_exceptions=False) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 193 | |
| 194 | Return a Future aggregating results from the given coroutine objects, |
| 195 | Tasks, or Futures. |
| 196 | |
| 197 | If all Tasks/Futures are completed successfully, the result is an |
| 198 | aggregate list of returned values. The result values are in the |
| 199 | order of the original *fs* sequence. |
| 200 | |
| 201 | All coroutines in the *fs* list are automatically |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 202 | scheduled as :class:`Tasks <Task>`. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 203 | |
| 204 | If *return_exceptions* is ``True``, exceptions in the Tasks/Futures |
| 205 | are treated the same as successful results, and gathered in the |
| 206 | result list. Otherwise, the first raised exception is immediately |
| 207 | propagated to the returned Future. |
| 208 | |
| 209 | If the outer Future is *cancelled*, all submitted Tasks/Futures |
| 210 | (that have not completed yet) are also *cancelled*. |
| 211 | |
| 212 | If any child is *cancelled*, it is treated as if it raised |
| 213 | :exc:`CancelledError` -- the outer Future is **not** cancelled in |
| 214 | this case. This is to prevent the cancellation of one submitted |
| 215 | Task/Future to cause other Tasks/Futures to be cancelled. |
| 216 | |
| 217 | All futures must share the same event loop. |
| 218 | |
| 219 | .. versionchanged:: 3.7 |
| 220 | If the *gather* itself is cancelled, the cancellation is |
| 221 | propagated regardless of *return_exceptions*. |
| 222 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 223 | .. _asyncio_example_gather: |
| 224 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 225 | Example:: |
| 226 | |
| 227 | import asyncio |
| 228 | |
| 229 | async def factorial(name, number): |
| 230 | f = 1 |
| 231 | for i in range(2, number + 1): |
| 232 | print(f"Task {name}: Compute factorial({i})...") |
| 233 | await asyncio.sleep(1) |
| 234 | f *= i |
| 235 | print(f"Task {name}: factorial({number}) = {f}") |
| 236 | |
| 237 | async def main(): |
| 238 | await asyncio.gather( |
| 239 | factorial("A", 2), |
| 240 | factorial("B", 3), |
| 241 | factorial("C", 4), |
Miguel Ángel García | 9c53fa6 | 2018-09-18 08:01:26 +0200 | [diff] [blame] | 242 | ) |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 243 | |
| 244 | asyncio.run(main()) |
| 245 | |
| 246 | # Expected output: |
| 247 | # |
| 248 | # Task A: Compute factorial(2)... |
| 249 | # Task B: Compute factorial(2)... |
| 250 | # Task C: Compute factorial(2)... |
| 251 | # Task A: factorial(2) = 2 |
| 252 | # Task B: Compute factorial(3)... |
| 253 | # Task C: Compute factorial(3)... |
| 254 | # Task B: factorial(3) = 6 |
| 255 | # Task C: Compute factorial(4)... |
| 256 | # Task C: factorial(4) = 24 |
| 257 | |
| 258 | |
| 259 | Shielding Tasks From Cancellation |
| 260 | ================================= |
| 261 | |
| 262 | .. coroutinefunction:: shield(fut, \*, loop=None) |
| 263 | |
| 264 | Wait for a Future/Task while protecting it from being cancelled. |
| 265 | |
| 266 | *fut* can be a coroutine, a Task, or a Future-like object. If |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 267 | *fut* is a coroutine it is automatically scheduled as a |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 268 | :class:`Task`. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 269 | |
| 270 | The statement:: |
| 271 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 272 | res = await shield(something()) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 273 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 274 | is equivalent to:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 275 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 276 | res = await something() |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 277 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 278 | *except* that if the coroutine containing it is cancelled, the |
| 279 | Task running in ``something()`` is not cancelled. From the point |
| 280 | of view of ``something()``, the cancellation did not happen. |
| 281 | Although its caller is still cancelled, so the "await" expression |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 282 | still raises a :exc:`CancelledError`. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 283 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 284 | If ``something()`` is cancelled by other means (i.e. from within |
| 285 | itself) that would also cancel ``shield()``. |
| 286 | |
| 287 | If it is desired to completely ignore cancellation (not recommended) |
| 288 | the ``shield()`` function should be combined with a try/except |
| 289 | clause, as follows:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 290 | |
| 291 | try: |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 292 | res = await shield(something()) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 293 | except CancelledError: |
| 294 | res = None |
| 295 | |
Yury Selivanov | 950204d | 2016-05-16 16:23:00 -0400 | [diff] [blame] | 296 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 297 | Timeouts |
| 298 | ======== |
| 299 | |
| 300 | .. coroutinefunction:: wait_for(fut, timeout, \*, loop=None) |
| 301 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 302 | Wait for a coroutine, Task, or Future to complete with timeout. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 303 | |
| 304 | *fut* can be a coroutine, a Task, or a Future-like object. If |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 305 | *fut* is a coroutine it is automatically scheduled as a |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 306 | :class:`Task`. |
| 307 | |
| 308 | *timeout* can either be ``None`` or a float or int number of seconds |
| 309 | to wait for. If *timeout* is ``None``, block until the future |
| 310 | completes. |
| 311 | |
| 312 | If a timeout occurs, it cancels the task and raises |
| 313 | :exc:`asyncio.TimeoutError`. |
| 314 | |
| 315 | To avoid the task cancellation, wrap it in :func:`shield`. |
| 316 | |
| 317 | The function will wait until the future is actually cancelled, |
| 318 | so the total wait time may exceed the *timeout*. |
| 319 | |
| 320 | If the wait is cancelled, the future *fut* is also cancelled. |
| 321 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 322 | .. _asyncio_example_waitfor: |
| 323 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 324 | Example:: |
| 325 | |
| 326 | async def eternity(): |
| 327 | # Sleep for one hour |
| 328 | await asyncio.sleep(3600) |
| 329 | print('yay!') |
| 330 | |
| 331 | async def main(): |
| 332 | # Wait for at most 1 second |
| 333 | try: |
| 334 | await asyncio.wait_for(eternity(), timeout=1.0) |
| 335 | except asyncio.TimeoutError: |
| 336 | print('timeout!') |
| 337 | |
| 338 | asyncio.run(main()) |
| 339 | |
| 340 | # Expected output: |
| 341 | # |
| 342 | # timeout! |
| 343 | |
| 344 | .. versionchanged:: 3.7 |
| 345 | When *fut* is cancelled due to a timeout, ``wait_for`` waits |
| 346 | for *fut* to be cancelled. Previously, it raised |
| 347 | :exc:`asyncio.TimeoutError` immediately. |
| 348 | |
| 349 | |
| 350 | Waiting Primitives |
| 351 | ================== |
| 352 | |
| 353 | .. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\ |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 354 | return_when=ALL_COMPLETED) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 355 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 356 | Wait for a set of coroutines, Tasks, or Futures to complete. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 357 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 358 | *fs* is a list of coroutines, Futures, and/or Tasks. Coroutines |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 359 | are automatically scheduled as :class:`Tasks <Task>`. |
Victor Stinner | db74d98 | 2014-06-10 11:16:05 +0200 | [diff] [blame] | 360 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 361 | Returns two sets of Tasks/Futures: ``(done, pending)``. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 362 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 363 | *timeout* (a float or int), if specified, can be used to control |
| 364 | the maximum number of seconds to wait before returning. |
| 365 | |
| 366 | Note that this function does not raise :exc:`asyncio.TimeoutError`. |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 367 | Futures or Tasks that aren't done when the timeout occurs are simply |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 368 | returned in the second set. |
| 369 | |
| 370 | *return_when* indicates when this function should return. It must |
| 371 | be one of the following constants: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 372 | |
| 373 | .. tabularcolumns:: |l|L| |
| 374 | |
| 375 | +-----------------------------+----------------------------------------+ |
| 376 | | Constant | Description | |
| 377 | +=============================+========================================+ |
| 378 | | :const:`FIRST_COMPLETED` | The function will return when any | |
| 379 | | | future finishes or is cancelled. | |
| 380 | +-----------------------------+----------------------------------------+ |
| 381 | | :const:`FIRST_EXCEPTION` | The function will return when any | |
| 382 | | | future finishes by raising an | |
| 383 | | | exception. If no future raises an | |
| 384 | | | exception then it is equivalent to | |
| 385 | | | :const:`ALL_COMPLETED`. | |
| 386 | +-----------------------------+----------------------------------------+ |
| 387 | | :const:`ALL_COMPLETED` | The function will return when all | |
| 388 | | | futures finish or are cancelled. | |
| 389 | +-----------------------------+----------------------------------------+ |
| 390 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 391 | Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the |
| 392 | futures when a timeout occurs. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 393 | |
| 394 | Usage:: |
| 395 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 396 | done, pending = await asyncio.wait(fs) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 397 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 398 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 399 | .. function:: as_completed(fs, \*, loop=None, timeout=None) |
| 400 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 401 | Return an iterator of awaitables which return |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 402 | :class:`Future` instances. |
| 403 | |
| 404 | Raises :exc:`asyncio.TimeoutError` if the timeout occurs before |
| 405 | all Futures are done. |
| 406 | |
| 407 | Example:: |
| 408 | |
| 409 | for f in as_completed(fs): |
| 410 | result = await f |
| 411 | # ... |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 412 | |
Victor Stinner | 3e09e32 | 2013-12-03 01:22:06 +0100 | [diff] [blame] | 413 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 414 | Scheduling From Other Threads |
| 415 | ============================= |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 416 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 417 | .. function:: run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 418 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 419 | Submit a coroutine to the given event loop. Thread-safe. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 420 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 421 | Return a :class:`concurrent.futures.Future` to access the result. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 422 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 423 | This function is meant to be called from a different OS thread |
| 424 | than the one where the event loop is running. Example:: |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 425 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 426 | # Create a coroutine |
| 427 | coro = asyncio.sleep(1, result=3) |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 428 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 429 | # Submit the coroutine to a given loop |
| 430 | future = asyncio.run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 431 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 432 | # Wait for the result with an optional timeout argument |
| 433 | assert future.result(timeout) == 3 |
| 434 | |
| 435 | If an exception is raised in the coroutine, the returned Future |
| 436 | will be notified. It can also be used to cancel the task in |
| 437 | the event loop:: |
| 438 | |
| 439 | try: |
| 440 | result = future.result(timeout) |
| 441 | except asyncio.TimeoutError: |
| 442 | print('The coroutine took too long, cancelling the task...') |
| 443 | future.cancel() |
| 444 | except Exception as exc: |
| 445 | print('The coroutine raised an exception: {!r}'.format(exc)) |
| 446 | else: |
| 447 | print('The coroutine returned: {!r}'.format(result)) |
| 448 | |
| 449 | See the :ref:`concurrency and multithreading <asyncio-multithreading>` |
| 450 | section of the documentation. |
| 451 | |
| 452 | Unlike other asyncio functions this functions requires the *loop* |
| 453 | argument to be passed explicitly. |
| 454 | |
| 455 | .. versionadded:: 3.5.1 |
| 456 | |
| 457 | |
| 458 | Introspection |
| 459 | ============= |
| 460 | |
| 461 | |
| 462 | .. function:: current_task(loop=None) |
| 463 | |
| 464 | Return the currently running :class:`Task` instance, or ``None`` if |
| 465 | no task is running. |
| 466 | |
| 467 | If *loop* is ``None`` :func:`get_running_loop` is used to get |
| 468 | the current loop. |
| 469 | |
| 470 | .. versionadded:: 3.7 |
| 471 | |
| 472 | |
| 473 | .. function:: all_tasks(loop=None) |
| 474 | |
| 475 | Return a set of not yet finished :class:`Task` objects run by |
| 476 | the loop. |
| 477 | |
| 478 | If *loop* is ``None``, :func:`get_running_loop` is used for getting |
| 479 | current loop. |
| 480 | |
| 481 | .. versionadded:: 3.7 |
| 482 | |
| 483 | |
| 484 | Task Object |
| 485 | =========== |
| 486 | |
| 487 | .. class:: Task(coro, \*, loop=None, name=None) |
| 488 | |
| 489 | A :class:`Future`-like object that wraps a Python |
| 490 | :ref:`coroutine <coroutine>`. Not thread-safe. |
| 491 | |
| 492 | Tasks are used to run coroutines in event loops. |
| 493 | If a coroutine awaits on a Future, the Task suspends |
| 494 | the execution of the coroutine and waits for the completion |
| 495 | of the Future. When the Future is *done*, the execution of |
| 496 | the wrapped coroutine resumes. |
| 497 | |
| 498 | Event loops use cooperative scheduling: an event loop runs |
| 499 | one Task at a time. While a Task awaits for the completion of a |
| 500 | Future, the event loop runs other Tasks, callbacks, or performs |
| 501 | IO operations. |
| 502 | |
| 503 | Use the high-level :func:`asyncio.create_task` function to create |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 504 | Tasks, or the low-level :meth:`loop.create_task` or |
| 505 | :func:`ensure_future` functions. Manual instantiation of Tasks |
| 506 | is discouraged. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 507 | |
| 508 | To cancel a running Task use the :meth:`cancel` method. Calling it |
| 509 | will cause the Task to throw a :exc:`CancelledError` exception into |
| 510 | the wrapped coroutine. If a coroutine is awaiting on a Future |
| 511 | object during cancellation, the Future object will be cancelled. |
| 512 | |
| 513 | :meth:`cancelled` can be used to check if the Task was cancelled. |
| 514 | The method returns ``True`` if the wrapped coroutine did not |
| 515 | suppress the :exc:`CancelledError` exception and was actually |
| 516 | cancelled. |
| 517 | |
| 518 | :class:`asyncio.Task` inherits from :class:`Future` all of its |
| 519 | APIs except :meth:`Future.set_result` and |
| 520 | :meth:`Future.set_exception`. |
| 521 | |
| 522 | Tasks support the :mod:`contextvars` module. When a Task |
| 523 | is created it copies the current context and later runs its |
| 524 | coroutine in the copied context. |
Elvis Pranskevichus | e2b340a | 2018-05-29 17:31:01 -0400 | [diff] [blame] | 525 | |
| 526 | .. versionchanged:: 3.7 |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 527 | Added support for the :mod:`contextvars` module. |
| 528 | |
| 529 | .. versionchanged:: 3.8 |
| 530 | Added the ``name`` parameter. |
| 531 | |
| 532 | .. method:: cancel() |
| 533 | |
| 534 | Request the Task to be cancelled. |
| 535 | |
| 536 | This arranges for a :exc:`CancelledError` exception to be thrown |
| 537 | into the wrapped coroutine on the next cycle of the event loop. |
| 538 | |
| 539 | The coroutine then has a chance to clean up or even deny the |
| 540 | request by suppressing the exception with a :keyword:`try` ... |
| 541 | ... ``except CancelledError`` ... :keyword:`finally` block. |
| 542 | Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does |
| 543 | not guarantee that the Task will be cancelled, although |
| 544 | suppressing cancellation completely is not common and is actively |
| 545 | discouraged. |
| 546 | |
Yury Selivanov | 7372c3b | 2018-09-14 15:11:24 -0700 | [diff] [blame] | 547 | .. _asyncio_example_task_cancel: |
| 548 | |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 549 | The following example illustrates how coroutines can intercept |
| 550 | the cancellation request:: |
| 551 | |
| 552 | async def cancel_me(): |
| 553 | print('cancel_me(): before sleep') |
| 554 | |
| 555 | try: |
| 556 | # Wait for 1 hour |
| 557 | await asyncio.sleep(3600) |
| 558 | except asyncio.CancelledError: |
| 559 | print('cancel_me(): cancel sleep') |
| 560 | raise |
| 561 | finally: |
| 562 | print('cancel_me(): after sleep') |
| 563 | |
| 564 | async def main(): |
| 565 | # Create a "cancel_me" Task |
| 566 | task = asyncio.create_task(cancel_me()) |
| 567 | |
| 568 | # Wait for 1 second |
| 569 | await asyncio.sleep(1) |
| 570 | |
| 571 | task.cancel() |
| 572 | try: |
| 573 | await task |
| 574 | except asyncio.CancelledError: |
| 575 | print("main(): cancel_me is cancelled now") |
| 576 | |
| 577 | asyncio.run(main()) |
| 578 | |
| 579 | # Expected output: |
| 580 | # |
| 581 | # cancel_me(): before sleep |
| 582 | # cancel_me(): cancel sleep |
| 583 | # cancel_me(): after sleep |
| 584 | # main(): cancel_me is cancelled now |
| 585 | |
| 586 | .. method:: cancelled() |
| 587 | |
| 588 | Return ``True`` if the Task is *cancelled*. |
| 589 | |
| 590 | The Task is *cancelled* when the cancellation was requested with |
| 591 | :meth:`cancel` and the wrapped coroutine propagated the |
| 592 | :exc:`CancelledError` exception thrown into it. |
| 593 | |
| 594 | .. method:: done() |
| 595 | |
| 596 | Return ``True`` if the Task is *done*. |
| 597 | |
| 598 | A Task is *done* when the wrapped coroutine either returned |
| 599 | a value, raised an exception, or the Task was cancelled. |
| 600 | |
| 601 | .. method:: get_stack(\*, limit=None) |
| 602 | |
| 603 | Return the list of stack frames for this Task. |
| 604 | |
| 605 | If the wrapped coroutine is not done, this returns the stack |
| 606 | where it is suspended. If the coroutine has completed |
| 607 | successfully or was cancelled, this returns an empty list. |
| 608 | If the coroutine was terminated by an exception, this returns |
| 609 | the list of traceback frames. |
| 610 | |
| 611 | The frames are always ordered from oldest to newest. |
| 612 | |
| 613 | Only one stack frame is returned for a suspended coroutine. |
| 614 | |
| 615 | The optional *limit* argument sets the maximum number of frames |
| 616 | to return; by default all available frames are returned. |
| 617 | The ordering of the returned list differs depending on whether |
| 618 | a stack or a traceback is returned: the newest frames of a |
| 619 | stack are returned, but the oldest frames of a traceback are |
| 620 | returned. (This matches the behavior of the traceback module.) |
| 621 | |
| 622 | .. method:: print_stack(\*, limit=None, file=None) |
| 623 | |
| 624 | Print the stack or traceback for this Task. |
| 625 | |
| 626 | This produces output similar to that of the traceback module |
| 627 | for the frames retrieved by :meth:`get_stack`. |
| 628 | |
| 629 | The *limit* argument is passed to :meth:`get_stack` directly. |
| 630 | |
| 631 | The *file* argument is an I/O stream to which the output |
| 632 | is written; by default output is written to :data:`sys.stderr`. |
| 633 | |
| 634 | .. method:: get_name() |
| 635 | |
| 636 | Return the name of the Task. |
| 637 | |
| 638 | If no name has been explicitly assigned to the Task, the default |
| 639 | asyncio Task implementation generates a default name during |
| 640 | instantiation. |
| 641 | |
| 642 | .. versionadded:: 3.8 |
| 643 | |
| 644 | .. method:: set_name(value) |
| 645 | |
| 646 | Set the name of the Task. |
| 647 | |
| 648 | The *value* argument can be any object, which is then |
| 649 | converted to a string. |
| 650 | |
| 651 | In the default Task implementation, the name will be visible |
| 652 | in the :func:`repr` output of a task object. |
| 653 | |
| 654 | .. versionadded:: 3.8 |
| 655 | |
| 656 | .. classmethod:: all_tasks(loop=None) |
| 657 | |
| 658 | Return a set of all tasks for an event loop. |
| 659 | |
| 660 | By default all tasks for the current event loop are returned. |
| 661 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 662 | is used to get the current loop. |
| 663 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 664 | This method is **deprecated** and will be removed in |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 665 | Python 3.9. Use the :func:`all_tasks` function instead. |
| 666 | |
| 667 | .. classmethod:: current_task(loop=None) |
| 668 | |
| 669 | Return the currently running task or ``None``. |
| 670 | |
| 671 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 672 | is used to get the current loop. |
| 673 | |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 674 | This method is **deprecated** and will be removed in |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 675 | Python 3.9. Use the :func:`current_task` function instead. |
| 676 | |
| 677 | |
| 678 | .. _asyncio_generator_based_coro: |
| 679 | |
| 680 | Generator-based Coroutines |
| 681 | ========================== |
| 682 | |
| 683 | .. note:: |
| 684 | |
| 685 | Support for generator-based coroutines is **deprecated** and |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 686 | is scheduled for removal in Python 4.0. |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 687 | |
| 688 | Generator-based coroutines predate async/await syntax. They are |
Elvis Pranskevichus | 1fa2ec4 | 2018-09-17 19:16:44 -0400 | [diff] [blame] | 689 | Python generators that use ``yield from`` expressions to await |
Yury Selivanov | 3faaa88 | 2018-09-14 13:32:07 -0700 | [diff] [blame] | 690 | on Futures and other coroutines. |
| 691 | |
| 692 | Generator-based coroutines should be decorated with |
| 693 | :func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not |
| 694 | enforced. |
| 695 | |
| 696 | |
| 697 | .. decorator:: coroutine |
| 698 | |
| 699 | Decorator to mark generator-based coroutines. |
| 700 | |
| 701 | This decorator enables legacy generator-based coroutines to be |
| 702 | compatible with async/await code:: |
| 703 | |
| 704 | @asyncio.coroutine |
| 705 | def old_style_coroutine(): |
| 706 | yield from asyncio.sleep(1) |
| 707 | |
| 708 | async def main(): |
| 709 | await old_style_coroutine() |
| 710 | |
| 711 | This decorator is **deprecated** and is scheduled for removal in |
| 712 | Python 4.0. |
| 713 | |
| 714 | This decorator should not be used for :keyword:`async def` |
| 715 | coroutines. |
| 716 | |
| 717 | .. function:: iscoroutine(obj) |
| 718 | |
| 719 | Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`. |
| 720 | |
| 721 | This method is different from :func:`inspect.iscoroutine` because |
| 722 | it returns ``True`` for generator-based coroutines decorated with |
| 723 | :func:`@coroutine <coroutine>`. |
| 724 | |
| 725 | .. function:: iscoroutinefunction(func) |
| 726 | |
| 727 | Return ``True`` if *func* is a :ref:`coroutine function |
| 728 | <coroutine>`. |
| 729 | |
| 730 | This method is different from :func:`inspect.iscoroutinefunction` |
| 731 | because it returns ``True`` for generator-based coroutine functions |
| 732 | decorated with :func:`@coroutine <coroutine>`. |