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