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 | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 3 | |
| 4 | ==================== |
| 5 | Coroutines and Tasks |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 6 | ==================== |
| 7 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 19 | ========== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 20 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 21 | Coroutines declared with async/await syntax is the preferred way of |
| 22 | writing asyncio applications. For example, the following snippet |
Miss Islington (bot) | 45452b7 | 2018-09-18 00:00:58 -0700 | [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 | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 26 | >>> import asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 27 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 45 | * The :func:`asyncio.run` function to run the top-level |
| 46 | entry point "main()" function (see the above example.) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 47 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 48 | * Awaiting on a coroutine. The following snippet of code will |
| 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 | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 52 | import asyncio |
| 53 | import time |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 54 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | |
| 76 | * The :func:`asyncio.create_task` function to run coroutines |
| 77 | concurrently as asyncio :class:`Tasks <Task>`. |
| 78 | |
Miss Islington (bot) | 9a89fd6 | 2018-09-17 23:27:07 -0700 | [diff] [blame] | 79 | Let's modify the above example and run two ``say_after`` coroutines |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [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 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 106 | |
| 107 | .. _asyncio-awaitables: |
| 108 | |
| 109 | Awaitables |
| 110 | ========== |
| 111 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 112 | We say that an object is an **awaitable** object if it can be used |
| 113 | in an :keyword:`await` expression. Many asyncio APIs are designed to |
| 114 | accept awaitables. |
| 115 | |
| 116 | There are three main types of *awaitable* objects: |
| 117 | **coroutines**, **Tasks**, and **Futures**. |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 118 | |
| 119 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 120 | .. rubric:: Coroutines |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 121 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 122 | Python coroutines are *awaitables* and therefore can be awaited from |
| 123 | other coroutines:: |
| 124 | |
| 125 | import asyncio |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 126 | |
| 127 | async def nested(): |
| 128 | return 42 |
| 129 | |
| 130 | async def main(): |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 131 | # Nothing happens if we just call "nested()". |
| 132 | # (a coroutine object is created but not awaited) |
| 133 | nested() |
| 134 | |
| 135 | # Let's do it differently now and await it: |
| 136 | print(await nested()) # will print "42". |
| 137 | |
| 138 | asyncio.run(main()) |
| 139 | |
| 140 | .. important:: |
| 141 | |
| 142 | In this documentation the term "coroutine" can be used for |
| 143 | two closely related concepts: |
| 144 | |
| 145 | * a *coroutine function*: an :keyword:`async def` function; |
| 146 | |
| 147 | * a *coroutine object*: an object returned by calling a |
| 148 | *coroutine function*. |
| 149 | |
| 150 | asyncio also supports legacy :ref:`generator-based |
| 151 | <asyncio_generator_based_coro>` coroutines. |
| 152 | |
| 153 | |
| 154 | .. rubric:: Tasks |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 155 | |
| 156 | *Tasks* are used to schedule coroutines *concurrently*. |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 157 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 158 | When a coroutine is wrapped into a *Task* with functions like |
| 159 | :func:`asyncio.create_task` the coroutine is automatically |
| 160 | scheduled to run soon:: |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 161 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 162 | import asyncio |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 163 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 164 | async def nested(): |
| 165 | return 42 |
| 166 | |
| 167 | async def main(): |
| 168 | # Schedule nested() to run soon concurrently |
| 169 | # with "main()". |
| 170 | task = asyncio.create_task(nested()) |
| 171 | |
| 172 | # "task" can now be used to cancel "nested()", or |
| 173 | # can simply be awaited to wait until it is complete: |
| 174 | await task |
| 175 | |
| 176 | asyncio.run(main()) |
Victor Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 177 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 178 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 179 | .. rubric:: Futures |
| 180 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 181 | A :class:`Future` is a special **low-level** awaitable object that |
| 182 | represents an **eventual result** of an asynchronous operation. |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 183 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 184 | When a Future object is *awaited* it means that the coroutine will |
| 185 | wait until the Future is resolved in some other place. |
| 186 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 187 | Future objects in asyncio are needed to allow callback-based code |
| 188 | to be used with async/await. |
| 189 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 190 | Normally **there is no need** to create Future objects at the |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 191 | application level code. |
| 192 | |
| 193 | Future objects, sometimes exposed by libraries and some asyncio |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 194 | APIs, can be awaited:: |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 195 | |
| 196 | async def main(): |
| 197 | await function_that_returns_a_future_object() |
| 198 | |
| 199 | # this is also valid: |
| 200 | await asyncio.gather( |
| 201 | function_that_returns_a_future_object(), |
| 202 | some_python_coroutine() |
| 203 | ) |
| 204 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 205 | A good example of a low-level function that returns a Future object |
| 206 | is :meth:`loop.run_in_executor`. |
| 207 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 208 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 209 | Running an asyncio Program |
| 210 | ========================== |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 211 | |
Elvis Pranskevichus | 15f3d0c | 2018-05-19 23:39:45 -0400 | [diff] [blame] | 212 | .. function:: run(coro, \*, debug=False) |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 213 | |
| 214 | This function runs the passed coroutine, taking care of |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 215 | managing the asyncio event loop and *finalizing asynchronous |
| 216 | generators*. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 217 | |
| 218 | This function cannot be called when another asyncio event loop is |
| 219 | running in the same thread. |
| 220 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 221 | 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] | 222 | |
| 223 | This function always creates a new event loop and closes it at |
| 224 | the end. It should be used as a main entry point for asyncio |
| 225 | programs, and should ideally only be called once. |
| 226 | |
| 227 | .. versionadded:: 3.7 |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 228 | **Important:** this function has been added to asyncio in |
| 229 | Python 3.7 on a :term:`provisional basis <provisional api>`. |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 230 | |
| 231 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 232 | Creating Tasks |
| 233 | ============== |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 234 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 235 | .. function:: create_task(coro) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 236 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 237 | Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task` |
| 238 | and schedule its execution. Return the Task object. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 239 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 240 | The task is executed in the loop returned by :func:`get_running_loop`, |
| 241 | :exc:`RuntimeError` is raised if there is no running loop in |
| 242 | current thread. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 243 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 244 | This function has been **added in Python 3.7**. Prior to |
| 245 | Python 3.7, the low-level :func:`asyncio.ensure_future` function |
| 246 | can be used instead:: |
| 247 | |
| 248 | async def coro(): |
| 249 | ... |
| 250 | |
| 251 | # In Python 3.7+ |
| 252 | task = asyncio.create_task(coro()) |
| 253 | ... |
| 254 | |
| 255 | # This works in all Python versions but is less readable |
| 256 | task = asyncio.ensure_future(coro()) |
| 257 | ... |
| 258 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 259 | .. versionadded:: 3.7 |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 260 | |
| 261 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 262 | Sleeping |
| 263 | ======== |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 264 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 265 | .. coroutinefunction:: sleep(delay, result=None, \*, loop=None) |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 266 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 267 | Block for *delay* seconds. |
| 268 | |
| 269 | If *result* is provided, it is returned to the caller |
| 270 | when the coroutine completes. |
| 271 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 272 | The *loop* argument is deprecated and scheduled for removal |
| 273 | in Python 4.0. |
| 274 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 275 | .. _asyncio_example_sleep: |
| 276 | |
| 277 | Example of coroutine displaying the current date every second |
| 278 | for 5 seconds:: |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 279 | |
| 280 | import asyncio |
| 281 | import datetime |
| 282 | |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 283 | async def display_date(): |
| 284 | loop = asyncio.get_running_loop() |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 285 | end_time = loop.time() + 5.0 |
| 286 | while True: |
| 287 | print(datetime.datetime.now()) |
| 288 | if (loop.time() + 1.0) >= end_time: |
| 289 | break |
| 290 | await asyncio.sleep(1) |
| 291 | |
Yury Selivanov | 02a0a19 | 2017-12-14 09:42:21 -0500 | [diff] [blame] | 292 | asyncio.run(display_date()) |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 293 | |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 294 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 295 | Running Tasks Concurrently |
| 296 | ========================== |
Victor Stinner | 7f314ed | 2014-10-15 18:49:16 +0200 | [diff] [blame] | 297 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 298 | .. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False) |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 299 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 300 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 301 | sequence *concurrently*. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 302 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 303 | If any awaitable in *aws* is a coroutine, it is automatically |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 304 | scheduled as a Task. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 305 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 306 | If all awaitables are completed successfully, the result is an |
| 307 | aggregate list of returned values. The order of result values |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 308 | corresponds to the order of awaitables in *aws*. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 309 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 310 | If *return_exceptions* is ``True``, exceptions are treated the |
| 311 | same as successful results, and aggregated in the result list. |
| 312 | Otherwise, the first raised exception is immediately propagated |
| 313 | to the task that awaits on ``gather()``. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 314 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 315 | If ``gather`` is *cancelled*, all submitted awaitables |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 316 | (that have not completed yet) are also *cancelled*. |
Victor Stinner | b69d62d | 2013-12-10 02:09:46 +0100 | [diff] [blame] | 317 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 318 | If any Task or Future from the *aws* sequence is *cancelled*, it is |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 319 | treated as if it raised :exc:`CancelledError` -- the ``gather()`` |
| 320 | call is **not** cancelled in this case. This is to prevent the |
| 321 | cancellation of one submitted Task/Future to cause other |
| 322 | Tasks/Futures to be cancelled. |
Miss Islington (bot) | 2fc443c | 2018-05-23 10:59:17 -0700 | [diff] [blame] | 323 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 324 | .. _asyncio_example_gather: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 325 | |
| 326 | Example:: |
| 327 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 328 | import asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 329 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 330 | async def factorial(name, number): |
| 331 | f = 1 |
| 332 | for i in range(2, number + 1): |
| 333 | print(f"Task {name}: Compute factorial({i})...") |
| 334 | await asyncio.sleep(1) |
| 335 | f *= i |
| 336 | print(f"Task {name}: factorial({number}) = {f}") |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 337 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 338 | async def main(): |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 339 | # Schedule three calls *concurrently*: |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 340 | await asyncio.gather( |
| 341 | factorial("A", 2), |
| 342 | factorial("B", 3), |
| 343 | factorial("C", 4), |
Miss Islington (bot) | ee2ff1a | 2018-09-17 23:27:27 -0700 | [diff] [blame] | 344 | ) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 345 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 346 | asyncio.run(main()) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 347 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 348 | # Expected output: |
| 349 | # |
| 350 | # Task A: Compute factorial(2)... |
| 351 | # Task B: Compute factorial(2)... |
| 352 | # Task C: Compute factorial(2)... |
| 353 | # Task A: factorial(2) = 2 |
| 354 | # Task B: Compute factorial(3)... |
| 355 | # Task C: Compute factorial(3)... |
| 356 | # Task B: factorial(3) = 6 |
| 357 | # Task C: Compute factorial(4)... |
| 358 | # Task C: factorial(4) = 24 |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 359 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 360 | .. versionchanged:: 3.7 |
| 361 | If the *gather* itself is cancelled, the cancellation is |
| 362 | propagated regardless of *return_exceptions*. |
| 363 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 364 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 365 | Shielding Tasks From Cancellation |
| 366 | ================================= |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 367 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 368 | .. awaitablefunction:: shield(aw, \*, loop=None) |
Yury Selivanov | e319ab0 | 2015-12-15 00:45:24 -0500 | [diff] [blame] | 369 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 370 | Protect an :ref:`awaitable object <asyncio-awaitables>` |
| 371 | from being :meth:`cancelled <Task.cancel>`. |
Andrew Svetlov | f74ef45 | 2017-12-15 07:04:38 +0200 | [diff] [blame] | 372 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 373 | *aw* can be a coroutine, a Task, or a Future-like object. If |
| 374 | *aw* is a coroutine it is automatically scheduled as a Task. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 375 | |
| 376 | The statement:: |
| 377 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 378 | res = await shield(something()) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 379 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 380 | is equivalent to:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 381 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 382 | res = await something() |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 383 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 384 | *except* that if the coroutine containing it is cancelled, the |
| 385 | Task running in ``something()`` is not cancelled. From the point |
| 386 | of view of ``something()``, the cancellation did not happen. |
| 387 | Although its caller is still cancelled, so the "await" expression |
| 388 | still raises a :exc:`CancelledError`. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 389 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 390 | If ``something()`` is cancelled by other means (i.e. from within |
| 391 | itself) that would also cancel ``shield()``. |
| 392 | |
| 393 | If it is desired to completely ignore cancellation (not recommended) |
| 394 | the ``shield()`` function should be combined with a try/except |
| 395 | clause, as follows:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 396 | |
| 397 | try: |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 398 | res = await shield(something()) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 399 | except CancelledError: |
| 400 | res = None |
| 401 | |
Yury Selivanov | 950204d | 2016-05-16 16:23:00 -0400 | [diff] [blame] | 402 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 403 | Timeouts |
| 404 | ======== |
| 405 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 406 | .. coroutinefunction:: wait_for(aw, timeout, \*, loop=None) |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 407 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 408 | Wait for the *aw* :ref:`awaitable <asyncio-awaitables>` |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 409 | to complete with a timeout. |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 410 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 411 | If *aw* is a coroutine it is automatically scheduled as a Task. |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 412 | |
| 413 | *timeout* can either be ``None`` or a float or int number of seconds |
| 414 | to wait for. If *timeout* is ``None``, block until the future |
| 415 | completes. |
| 416 | |
| 417 | If a timeout occurs, it cancels the task and raises |
| 418 | :exc:`asyncio.TimeoutError`. |
| 419 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 420 | To avoid the task :meth:`cancellation <Task.cancel>`, |
| 421 | wrap it in :func:`shield`. |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 422 | |
| 423 | The function will wait until the future is actually cancelled, |
| 424 | so the total wait time may exceed the *timeout*. |
| 425 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 426 | If the wait is cancelled, the future *aw* is also cancelled. |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 427 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 428 | The *loop* argument is deprecated and scheduled for removal |
| 429 | in Python 4.0. |
| 430 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 431 | .. _asyncio_example_waitfor: |
| 432 | |
| 433 | Example:: |
| 434 | |
| 435 | async def eternity(): |
| 436 | # Sleep for one hour |
| 437 | await asyncio.sleep(3600) |
| 438 | print('yay!') |
| 439 | |
| 440 | async def main(): |
| 441 | # Wait for at most 1 second |
| 442 | try: |
| 443 | await asyncio.wait_for(eternity(), timeout=1.0) |
| 444 | except asyncio.TimeoutError: |
| 445 | print('timeout!') |
| 446 | |
| 447 | asyncio.run(main()) |
| 448 | |
| 449 | # Expected output: |
| 450 | # |
| 451 | # timeout! |
| 452 | |
| 453 | .. versionchanged:: 3.7 |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 454 | When *aw* is cancelled due to a timeout, ``wait_for`` waits |
| 455 | for *aw* to be cancelled. Previously, it raised |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 456 | :exc:`asyncio.TimeoutError` immediately. |
| 457 | |
| 458 | |
| 459 | Waiting Primitives |
| 460 | ================== |
| 461 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 462 | .. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\ |
Andrew Svetlov | f124016 | 2016-01-11 14:40:35 +0200 | [diff] [blame] | 463 | return_when=ALL_COMPLETED) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 464 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 465 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 466 | sequence concurrently and block until the condition specified |
| 467 | by *return_when*. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 468 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 469 | If any awaitable in *aws* is a coroutine, it is automatically |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 470 | scheduled as a Task. |
Victor Stinner | db74d98 | 2014-06-10 11:16:05 +0200 | [diff] [blame] | 471 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 472 | Returns two sets of Tasks/Futures: ``(done, pending)``. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 473 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 474 | The *loop* argument is deprecated and scheduled for removal |
| 475 | in Python 4.0. |
| 476 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 477 | *timeout* (a float or int), if specified, can be used to control |
| 478 | the maximum number of seconds to wait before returning. |
| 479 | |
| 480 | Note that this function does not raise :exc:`asyncio.TimeoutError`. |
| 481 | Futures or Tasks that aren't done when the timeout occurs are simply |
| 482 | returned in the second set. |
| 483 | |
| 484 | *return_when* indicates when this function should return. It must |
| 485 | be one of the following constants: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 486 | |
| 487 | .. tabularcolumns:: |l|L| |
| 488 | |
| 489 | +-----------------------------+----------------------------------------+ |
| 490 | | Constant | Description | |
| 491 | +=============================+========================================+ |
| 492 | | :const:`FIRST_COMPLETED` | The function will return when any | |
| 493 | | | future finishes or is cancelled. | |
| 494 | +-----------------------------+----------------------------------------+ |
| 495 | | :const:`FIRST_EXCEPTION` | The function will return when any | |
| 496 | | | future finishes by raising an | |
| 497 | | | exception. If no future raises an | |
| 498 | | | exception then it is equivalent to | |
| 499 | | | :const:`ALL_COMPLETED`. | |
| 500 | +-----------------------------+----------------------------------------+ |
| 501 | | :const:`ALL_COMPLETED` | The function will return when all | |
| 502 | | | futures finish or are cancelled. | |
| 503 | +-----------------------------+----------------------------------------+ |
| 504 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 505 | Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the |
| 506 | futures when a timeout occurs. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 507 | |
| 508 | Usage:: |
| 509 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 510 | done, pending = await asyncio.wait(aws) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 511 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 512 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 513 | .. function:: as_completed(aws, \*, loop=None, timeout=None) |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 514 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 515 | Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 516 | set concurrently. Return an iterator of :class:`Future` objects. |
| 517 | Each Future object returned represents the earliest result |
| 518 | from the set of the remaining awaitables. |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 519 | |
| 520 | Raises :exc:`asyncio.TimeoutError` if the timeout occurs before |
| 521 | all Futures are done. |
| 522 | |
| 523 | Example:: |
| 524 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 525 | for f in as_completed(aws): |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 526 | earliest_result = await f |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 527 | # ... |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 528 | |
Victor Stinner | 3e09e32 | 2013-12-03 01:22:06 +0100 | [diff] [blame] | 529 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 530 | Scheduling From Other Threads |
| 531 | ============================= |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 532 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 533 | .. function:: run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 534 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 535 | Submit a coroutine to the given event loop. Thread-safe. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 536 | |
Miss Islington (bot) | 73c0006 | 2018-09-18 15:09:51 -0700 | [diff] [blame] | 537 | Return a :class:`concurrent.futures.Future` to wait for the result |
| 538 | from another OS thread. |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 539 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 540 | This function is meant to be called from a different OS thread |
| 541 | than the one where the event loop is running. Example:: |
Victor Stinner | 72dcb0a | 2015-04-03 17:08:19 +0200 | [diff] [blame] | 542 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 543 | # Create a coroutine |
| 544 | coro = asyncio.sleep(1, result=3) |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 545 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 546 | # Submit the coroutine to a given loop |
| 547 | future = asyncio.run_coroutine_threadsafe(coro, loop) |
Victor Stinner | 1ad5afc | 2014-01-30 00:18:50 +0100 | [diff] [blame] | 548 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 549 | # Wait for the result with an optional timeout argument |
| 550 | assert future.result(timeout) == 3 |
| 551 | |
| 552 | If an exception is raised in the coroutine, the returned Future |
| 553 | will be notified. It can also be used to cancel the task in |
| 554 | the event loop:: |
| 555 | |
| 556 | try: |
| 557 | result = future.result(timeout) |
| 558 | except asyncio.TimeoutError: |
| 559 | print('The coroutine took too long, cancelling the task...') |
| 560 | future.cancel() |
| 561 | except Exception as exc: |
| 562 | print('The coroutine raised an exception: {!r}'.format(exc)) |
| 563 | else: |
| 564 | print('The coroutine returned: {!r}'.format(result)) |
| 565 | |
| 566 | See the :ref:`concurrency and multithreading <asyncio-multithreading>` |
| 567 | section of the documentation. |
| 568 | |
| 569 | Unlike other asyncio functions this functions requires the *loop* |
| 570 | argument to be passed explicitly. |
| 571 | |
| 572 | .. versionadded:: 3.5.1 |
| 573 | |
| 574 | |
| 575 | Introspection |
| 576 | ============= |
| 577 | |
| 578 | |
| 579 | .. function:: current_task(loop=None) |
| 580 | |
| 581 | Return the currently running :class:`Task` instance, or ``None`` if |
| 582 | no task is running. |
| 583 | |
| 584 | If *loop* is ``None`` :func:`get_running_loop` is used to get |
| 585 | the current loop. |
| 586 | |
| 587 | .. versionadded:: 3.7 |
| 588 | |
| 589 | |
| 590 | .. function:: all_tasks(loop=None) |
| 591 | |
| 592 | Return a set of not yet finished :class:`Task` objects run by |
| 593 | the loop. |
| 594 | |
| 595 | If *loop* is ``None``, :func:`get_running_loop` is used for getting |
| 596 | current loop. |
| 597 | |
| 598 | .. versionadded:: 3.7 |
| 599 | |
| 600 | |
| 601 | Task Object |
| 602 | =========== |
| 603 | |
| 604 | .. class:: Task(coro, \*, loop=None) |
| 605 | |
| 606 | A :class:`Future`-like object that wraps a Python |
| 607 | :ref:`coroutine <coroutine>`. Not thread-safe. |
| 608 | |
| 609 | Tasks are used to run coroutines in event loops. |
| 610 | If a coroutine awaits on a Future, the Task suspends |
| 611 | the execution of the coroutine and waits for the completion |
| 612 | of the Future. When the Future is *done*, the execution of |
| 613 | the wrapped coroutine resumes. |
| 614 | |
| 615 | Event loops use cooperative scheduling: an event loop runs |
| 616 | one Task at a time. While a Task awaits for the completion of a |
| 617 | Future, the event loop runs other Tasks, callbacks, or performs |
| 618 | IO operations. |
| 619 | |
| 620 | Use the high-level :func:`asyncio.create_task` function to create |
| 621 | Tasks, or the low-level :meth:`loop.create_task` or |
| 622 | :func:`ensure_future` functions. Manual instantiation of Tasks |
| 623 | is discouraged. |
| 624 | |
| 625 | To cancel a running Task use the :meth:`cancel` method. Calling it |
| 626 | will cause the Task to throw a :exc:`CancelledError` exception into |
| 627 | the wrapped coroutine. If a coroutine is awaiting on a Future |
| 628 | object during cancellation, the Future object will be cancelled. |
| 629 | |
| 630 | :meth:`cancelled` can be used to check if the Task was cancelled. |
| 631 | The method returns ``True`` if the wrapped coroutine did not |
| 632 | suppress the :exc:`CancelledError` exception and was actually |
| 633 | cancelled. |
| 634 | |
| 635 | :class:`asyncio.Task` inherits from :class:`Future` all of its |
| 636 | APIs except :meth:`Future.set_result` and |
| 637 | :meth:`Future.set_exception`. |
| 638 | |
| 639 | Tasks support the :mod:`contextvars` module. When a Task |
| 640 | is created it copies the current context and later runs its |
| 641 | coroutine in the copied context. |
Miss Islington (bot) | d8948c5 | 2018-05-29 15:37:06 -0700 | [diff] [blame] | 642 | |
| 643 | .. versionchanged:: 3.7 |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 644 | Added support for the :mod:`contextvars` module. |
| 645 | |
| 646 | .. method:: cancel() |
| 647 | |
| 648 | Request the Task to be cancelled. |
| 649 | |
| 650 | This arranges for a :exc:`CancelledError` exception to be thrown |
| 651 | into the wrapped coroutine on the next cycle of the event loop. |
| 652 | |
| 653 | The coroutine then has a chance to clean up or even deny the |
| 654 | request by suppressing the exception with a :keyword:`try` ... |
| 655 | ... ``except CancelledError`` ... :keyword:`finally` block. |
| 656 | Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does |
| 657 | not guarantee that the Task will be cancelled, although |
| 658 | suppressing cancellation completely is not common and is actively |
| 659 | discouraged. |
| 660 | |
| 661 | .. _asyncio_example_task_cancel: |
| 662 | |
| 663 | The following example illustrates how coroutines can intercept |
| 664 | the cancellation request:: |
| 665 | |
| 666 | async def cancel_me(): |
| 667 | print('cancel_me(): before sleep') |
| 668 | |
| 669 | try: |
| 670 | # Wait for 1 hour |
| 671 | await asyncio.sleep(3600) |
| 672 | except asyncio.CancelledError: |
| 673 | print('cancel_me(): cancel sleep') |
| 674 | raise |
| 675 | finally: |
| 676 | print('cancel_me(): after sleep') |
| 677 | |
| 678 | async def main(): |
| 679 | # Create a "cancel_me" Task |
| 680 | task = asyncio.create_task(cancel_me()) |
| 681 | |
| 682 | # Wait for 1 second |
| 683 | await asyncio.sleep(1) |
| 684 | |
| 685 | task.cancel() |
| 686 | try: |
| 687 | await task |
| 688 | except asyncio.CancelledError: |
| 689 | print("main(): cancel_me is cancelled now") |
| 690 | |
| 691 | asyncio.run(main()) |
| 692 | |
| 693 | # Expected output: |
| 694 | # |
| 695 | # cancel_me(): before sleep |
| 696 | # cancel_me(): cancel sleep |
| 697 | # cancel_me(): after sleep |
| 698 | # main(): cancel_me is cancelled now |
| 699 | |
| 700 | .. method:: cancelled() |
| 701 | |
| 702 | Return ``True`` if the Task is *cancelled*. |
| 703 | |
| 704 | The Task is *cancelled* when the cancellation was requested with |
| 705 | :meth:`cancel` and the wrapped coroutine propagated the |
| 706 | :exc:`CancelledError` exception thrown into it. |
| 707 | |
| 708 | .. method:: done() |
| 709 | |
| 710 | Return ``True`` if the Task is *done*. |
| 711 | |
| 712 | A Task is *done* when the wrapped coroutine either returned |
| 713 | a value, raised an exception, or the Task was cancelled. |
| 714 | |
Miss Islington (bot) | 8e5ef58 | 2018-09-20 09:57:19 -0700 | [diff] [blame^] | 715 | .. method:: result() |
| 716 | |
| 717 | Return the result of the Task. |
| 718 | |
| 719 | If the Task is *done*, the result of the wrapped coroutine |
| 720 | is returned (or if the coroutine raised an exception, that |
| 721 | exception is re-raised.) |
| 722 | |
| 723 | If the Task has been *cancelled*, this method raises |
| 724 | a :exc:`CancelledError` exception. |
| 725 | |
| 726 | If the Task's result isn't yet available, this method raises |
| 727 | a :exc:`InvalidStateError` exception. |
| 728 | |
| 729 | .. method:: exception() |
| 730 | |
| 731 | Return the exception of the Task. |
| 732 | |
| 733 | If the wrapped coroutine raised an exception that exception |
| 734 | is returned. If the wrapped coroutine returned normally |
| 735 | this method returns ``None``. |
| 736 | |
| 737 | If the Task has been *cancelled*, this method raises a |
| 738 | :exc:`CancelledError` exception. |
| 739 | |
| 740 | If the Task isn't *done* yet, this method raises an |
| 741 | :exc:`InvalidStateError` exception. |
| 742 | |
| 743 | .. method:: add_done_callback(callback, *, context=None) |
| 744 | |
| 745 | Add a callback to be run when the Task is *done*. |
| 746 | |
| 747 | This method should only be used in low-level callback-based code. |
| 748 | |
| 749 | See the documentation of :meth:`Future.add_done_callback` |
| 750 | for more details. |
| 751 | |
| 752 | .. method:: remove_done_callback(callback) |
| 753 | |
| 754 | Remove *callback* from the callbacks list. |
| 755 | |
| 756 | This method should only be used in low-level callback-based code. |
| 757 | |
| 758 | See the documentation of :meth:`Future.remove_done_callback` |
| 759 | for more details. |
| 760 | |
Yury Selivanov | 512d710 | 2018-09-17 19:35:30 -0400 | [diff] [blame] | 761 | .. method:: get_stack(\*, limit=None) |
| 762 | |
| 763 | Return the list of stack frames for this Task. |
| 764 | |
| 765 | If the wrapped coroutine is not done, this returns the stack |
| 766 | where it is suspended. If the coroutine has completed |
| 767 | successfully or was cancelled, this returns an empty list. |
| 768 | If the coroutine was terminated by an exception, this returns |
| 769 | the list of traceback frames. |
| 770 | |
| 771 | The frames are always ordered from oldest to newest. |
| 772 | |
| 773 | Only one stack frame is returned for a suspended coroutine. |
| 774 | |
| 775 | The optional *limit* argument sets the maximum number of frames |
| 776 | to return; by default all available frames are returned. |
| 777 | The ordering of the returned list differs depending on whether |
| 778 | a stack or a traceback is returned: the newest frames of a |
| 779 | stack are returned, but the oldest frames of a traceback are |
| 780 | returned. (This matches the behavior of the traceback module.) |
| 781 | |
| 782 | .. method:: print_stack(\*, limit=None, file=None) |
| 783 | |
| 784 | Print the stack or traceback for this Task. |
| 785 | |
| 786 | This produces output similar to that of the traceback module |
| 787 | for the frames retrieved by :meth:`get_stack`. |
| 788 | |
| 789 | The *limit* argument is passed to :meth:`get_stack` directly. |
| 790 | |
| 791 | The *file* argument is an I/O stream to which the output |
| 792 | is written; by default output is written to :data:`sys.stderr`. |
| 793 | |
| 794 | .. classmethod:: all_tasks(loop=None) |
| 795 | |
| 796 | Return a set of all tasks for an event loop. |
| 797 | |
| 798 | By default all tasks for the current event loop are returned. |
| 799 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 800 | is used to get the current loop. |
| 801 | |
| 802 | This method is **deprecated** and will be removed in |
| 803 | Python 3.9. Use the :func:`all_tasks` function instead. |
| 804 | |
| 805 | .. classmethod:: current_task(loop=None) |
| 806 | |
| 807 | Return the currently running task or ``None``. |
| 808 | |
| 809 | If *loop* is ``None``, the :func:`get_event_loop` function |
| 810 | is used to get the current loop. |
| 811 | |
| 812 | This method is **deprecated** and will be removed in |
| 813 | Python 3.9. Use the :func:`current_task` function instead. |
| 814 | |
| 815 | |
| 816 | .. _asyncio_generator_based_coro: |
| 817 | |
| 818 | Generator-based Coroutines |
| 819 | ========================== |
| 820 | |
| 821 | .. note:: |
| 822 | |
| 823 | Support for generator-based coroutines is **deprecated** and |
| 824 | is scheduled for removal in Python 4.0. |
| 825 | |
| 826 | Generator-based coroutines predate async/await syntax. They are |
| 827 | Python generators that use ``yield from`` expressions to await |
| 828 | on Futures and other coroutines. |
| 829 | |
| 830 | Generator-based coroutines should be decorated with |
| 831 | :func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not |
| 832 | enforced. |
| 833 | |
| 834 | |
| 835 | .. decorator:: coroutine |
| 836 | |
| 837 | Decorator to mark generator-based coroutines. |
| 838 | |
| 839 | This decorator enables legacy generator-based coroutines to be |
| 840 | compatible with async/await code:: |
| 841 | |
| 842 | @asyncio.coroutine |
| 843 | def old_style_coroutine(): |
| 844 | yield from asyncio.sleep(1) |
| 845 | |
| 846 | async def main(): |
| 847 | await old_style_coroutine() |
| 848 | |
| 849 | This decorator is **deprecated** and is scheduled for removal in |
| 850 | Python 4.0. |
| 851 | |
| 852 | This decorator should not be used for :keyword:`async def` |
| 853 | coroutines. |
| 854 | |
| 855 | .. function:: iscoroutine(obj) |
| 856 | |
| 857 | Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`. |
| 858 | |
| 859 | This method is different from :func:`inspect.iscoroutine` because |
| 860 | it returns ``True`` for generator-based coroutines decorated with |
| 861 | :func:`@coroutine <coroutine>`. |
| 862 | |
| 863 | .. function:: iscoroutinefunction(func) |
| 864 | |
| 865 | Return ``True`` if *func* is a :ref:`coroutine function |
| 866 | <coroutine>`. |
| 867 | |
| 868 | This method is different from :func:`inspect.iscoroutinefunction` |
| 869 | because it returns ``True`` for generator-based coroutine functions |
| 870 | decorated with :func:`@coroutine <coroutine>`. |