blob: 4b079e81a2922df9421be9b214cd3c9901485945 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov512d7102018-09-17 19:35:30 -04003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov512d7102018-09-17 19:35:30 -04008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov512d7102018-09-17 19:35:30 -040011.. contents::
12 :depth: 1
13 :local:
14
lf627d2c82017-07-25 17:03:51 -060015
Victor Stinnerea3183f2013-12-03 01:08:00 +010016.. _coroutine:
17
18Coroutines
Yury Selivanov512d7102018-09-17 19:35:30 -040019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov512d7102018-09-17 19:35:30 -040021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
Miss Islington (bot)45452b72018-09-18 00:00:58 -070023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov512d7102018-09-17 19:35:30 -040026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov512d7102018-09-17 19:35:30 -040028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov512d7102018-09-17 19:35:30 -040033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov512d7102018-09-17 19:35:30 -040037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov512d7102018-09-17 19:35:30 -040040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Yury Selivanov512d7102018-09-17 19:35:30 -040043To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
Yury Selivanov512d7102018-09-17 19:35:30 -040045* The :func:`asyncio.run` function to run the top-level
46 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010047
Yury Selivanov512d7102018-09-17 19:35:30 -040048* 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 Stinnerea3183f2013-12-03 01:08:00 +010051
Yury Selivanov512d7102018-09-17 19:35:30 -040052 import asyncio
53 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010054
Yury Selivanov512d7102018-09-17 19:35:30 -040055 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)9a89fd62018-09-17 23:27:07 -070079 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov512d7102018-09-17 19:35:30 -040080 *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)73c00062018-09-18 15:09:51 -0700106
107.. _asyncio-awaitables:
108
109Awaitables
110==========
111
112We say that an object is an *awaitable* object if it can be used
113in an :keyword:`await` expression.
114
115
116.. rubric:: Coroutines and Tasks
117
118Python coroutines are *awaitables*::
119
120 async def nested():
121 return 42
122
123 async def main():
124 # Will print "42":
125 print(await nested())
126
127*Tasks* are used to schedule coroutines *concurrently*.
128See the previous :ref:`section <coroutine>` for an introduction
129to coroutines and tasks.
130
Yury Selivanov512d7102018-09-17 19:35:30 -0400131Note that in this documentation the term "coroutine" can be used for
132two closely related concepts:
133
134* a *coroutine function*: an :keyword:`async def` function;
135
136* a *coroutine object*: object returned by calling a
137 *coroutine function*.
Victor Stinner337e03f2014-08-11 01:11:13 +0200138
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700140.. rubric:: Futures
141
142There is a dedicated section about the :ref:`asyncio Future object
143<asyncio-futures>`, but the concept is fundamental to asyncio so
144it needs a brief introduction in this section.
145
146A Future is a special **low-level** awaitable object that represents
147an **eventual result** of an asynchronous operation.
148Future objects in asyncio are needed to allow callback-based code
149to be used with async/await.
150
151Normally, **there is no need** to create Future objects at the
152application level code.
153
154Future objects, sometimes exposed by libraries and some asyncio
155APIs, should be awaited::
156
157 async def main():
158 await function_that_returns_a_future_object()
159
160 # this is also valid:
161 await asyncio.gather(
162 function_that_returns_a_future_object(),
163 some_python_coroutine()
164 )
165
166
Yury Selivanov512d7102018-09-17 19:35:30 -0400167Running an asyncio Program
168==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100169
Elvis Pranskevichus15f3d0c2018-05-19 23:39:45 -0400170.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500171
172 This function runs the passed coroutine, taking care of
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700173 managing the asyncio event loop and *finalizing asynchronous
174 generators*.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500175
176 This function cannot be called when another asyncio event loop is
177 running in the same thread.
178
Yury Selivanov512d7102018-09-17 19:35:30 -0400179 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500180
181 This function always creates a new event loop and closes it at
182 the end. It should be used as a main entry point for asyncio
183 programs, and should ideally only be called once.
184
185 .. versionadded:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400186 **Important:** this function has been added to asyncio in
187 Python 3.7 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500188
189
Yury Selivanov512d7102018-09-17 19:35:30 -0400190Creating Tasks
191==============
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100192
Yury Selivanov512d7102018-09-17 19:35:30 -0400193.. function:: create_task(coro)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100194
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700195 Wrap the *coro* :ref:`coroutine <coroutine>` into a Task and
196 schedule its execution. Return the Task object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100197
Yury Selivanov512d7102018-09-17 19:35:30 -0400198 The task is executed in the loop returned by :func:`get_running_loop`,
199 :exc:`RuntimeError` is raised if there is no running loop in
200 current thread.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100201
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700202 This function has been **added in Python 3.7**. Prior to
203 Python 3.7, the low-level :func:`asyncio.ensure_future` function
204 can be used instead::
205
206 async def coro():
207 ...
208
209 # In Python 3.7+
210 task = asyncio.create_task(coro())
211 ...
212
213 # This works in all Python versions but is less readable
214 task = asyncio.ensure_future(coro())
215 ...
216
Yury Selivanov512d7102018-09-17 19:35:30 -0400217 .. versionadded:: 3.7
Victor Stinner7f314ed2014-10-15 18:49:16 +0200218
219
Yury Selivanov512d7102018-09-17 19:35:30 -0400220Sleeping
221========
Victor Stinner7f314ed2014-10-15 18:49:16 +0200222
Yury Selivanov512d7102018-09-17 19:35:30 -0400223.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinner7f314ed2014-10-15 18:49:16 +0200224
Yury Selivanov512d7102018-09-17 19:35:30 -0400225 Block for *delay* seconds.
226
227 If *result* is provided, it is returned to the caller
228 when the coroutine completes.
229
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700230 The *loop* argument is deprecated and scheduled for removal
231 in Python 4.0.
232
Yury Selivanov512d7102018-09-17 19:35:30 -0400233 .. _asyncio_example_sleep:
234
235 Example of coroutine displaying the current date every second
236 for 5 seconds::
Victor Stinner7f314ed2014-10-15 18:49:16 +0200237
238 import asyncio
239 import datetime
240
Yury Selivanov02a0a192017-12-14 09:42:21 -0500241 async def display_date():
242 loop = asyncio.get_running_loop()
Yury Selivanov66f88282015-06-24 11:04:15 -0400243 end_time = loop.time() + 5.0
244 while True:
245 print(datetime.datetime.now())
246 if (loop.time() + 1.0) >= end_time:
247 break
248 await asyncio.sleep(1)
249
Yury Selivanov02a0a192017-12-14 09:42:21 -0500250 asyncio.run(display_date())
Yury Selivanov66f88282015-06-24 11:04:15 -0400251
Victor Stinner7f314ed2014-10-15 18:49:16 +0200252
Yury Selivanov512d7102018-09-17 19:35:30 -0400253Running Tasks Concurrently
254==========================
Victor Stinner7f314ed2014-10-15 18:49:16 +0200255
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700256.. awaitablefunction:: gather(\*fs, loop=None, return_exceptions=False)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100257
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700258 Run :ref:`awaitable objects <asyncio-awaitables>` in the *fs*
259 sequence *concurrently*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100260
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700261 If any awaitable in *fs* is a coroutine, it is automatically
262 scheduled as a Task.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100263
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700264 If all awaitables are completed successfully, the result is an
265 aggregate list of returned values. The order of result values
266 corresponds to the order of awaitables in *fs*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100267
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700268 If *return_exceptions* is ``True``, exceptions are treated the
269 same as successful results, and aggregated in the result list.
270 Otherwise, the first raised exception is immediately propagated
271 to the task that awaits on ``gather()``.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100272
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700273 If ``gather`` is *cancelled*, all submitted awaitables
Yury Selivanov512d7102018-09-17 19:35:30 -0400274 (that have not completed yet) are also *cancelled*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100275
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700276 If any Task or Future from the *fs* sequence is *cancelled*, it is
277 treated as if it raised :exc:`CancelledError` -- the ``gather()``
278 call is **not** cancelled in this case. This is to prevent the
279 cancellation of one submitted Task/Future to cause other
280 Tasks/Futures to be cancelled.
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700281
Yury Selivanov512d7102018-09-17 19:35:30 -0400282 .. _asyncio_example_gather:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283
284 Example::
285
Yury Selivanov512d7102018-09-17 19:35:30 -0400286 import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287
Yury Selivanov512d7102018-09-17 19:35:30 -0400288 async def factorial(name, number):
289 f = 1
290 for i in range(2, number + 1):
291 print(f"Task {name}: Compute factorial({i})...")
292 await asyncio.sleep(1)
293 f *= i
294 print(f"Task {name}: factorial({number}) = {f}")
Victor Stinnerea3183f2013-12-03 01:08:00 +0100295
Yury Selivanov512d7102018-09-17 19:35:30 -0400296 async def main():
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700297 # Schedule three calls *concurrently*:
Yury Selivanov512d7102018-09-17 19:35:30 -0400298 await asyncio.gather(
299 factorial("A", 2),
300 factorial("B", 3),
301 factorial("C", 4),
Miss Islington (bot)ee2ff1a2018-09-17 23:27:27 -0700302 )
Victor Stinnerea3183f2013-12-03 01:08:00 +0100303
Yury Selivanov512d7102018-09-17 19:35:30 -0400304 asyncio.run(main())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100305
Yury Selivanov512d7102018-09-17 19:35:30 -0400306 # Expected output:
307 #
308 # Task A: Compute factorial(2)...
309 # Task B: Compute factorial(2)...
310 # Task C: Compute factorial(2)...
311 # Task A: factorial(2) = 2
312 # Task B: Compute factorial(3)...
313 # Task C: Compute factorial(3)...
314 # Task B: factorial(3) = 6
315 # Task C: Compute factorial(4)...
316 # Task C: factorial(4) = 24
Victor Stinnerea3183f2013-12-03 01:08:00 +0100317
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700318 .. versionchanged:: 3.7
319 If the *gather* itself is cancelled, the cancellation is
320 propagated regardless of *return_exceptions*.
321
Victor Stinnerea3183f2013-12-03 01:08:00 +0100322
Yury Selivanov512d7102018-09-17 19:35:30 -0400323Shielding Tasks From Cancellation
324=================================
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400325
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700326.. awaitablefunction:: shield(fut, \*, loop=None)
Yury Selivanove319ab02015-12-15 00:45:24 -0500327
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700328 Protect an :ref:`awaitable object <asyncio-awaitables>`
329 from being :meth:`cancelled <Task.cancel>`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200330
Yury Selivanov512d7102018-09-17 19:35:30 -0400331 *fut* can be a coroutine, a Task, or a Future-like object. If
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700332 *fut* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100333
334 The statement::
335
Andrew Svetlov88743422017-12-11 17:35:49 +0200336 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100337
Yury Selivanov512d7102018-09-17 19:35:30 -0400338 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100339
Andrew Svetlov88743422017-12-11 17:35:49 +0200340 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100341
Yury Selivanov512d7102018-09-17 19:35:30 -0400342 *except* that if the coroutine containing it is cancelled, the
343 Task running in ``something()`` is not cancelled. From the point
344 of view of ``something()``, the cancellation did not happen.
345 Although its caller is still cancelled, so the "await" expression
346 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100347
Yury Selivanov512d7102018-09-17 19:35:30 -0400348 If ``something()`` is cancelled by other means (i.e. from within
349 itself) that would also cancel ``shield()``.
350
351 If it is desired to completely ignore cancellation (not recommended)
352 the ``shield()`` function should be combined with a try/except
353 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100354
355 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200356 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100357 except CancelledError:
358 res = None
359
Yury Selivanov950204d2016-05-16 16:23:00 -0400360
Yury Selivanov512d7102018-09-17 19:35:30 -0400361Timeouts
362========
363
364.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
365
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700366 Wait for the *fut* :ref:`awaitable <asyncio-awaitables>`
367 to complete with a timeout.
Yury Selivanov512d7102018-09-17 19:35:30 -0400368
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700369 If *fut* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov512d7102018-09-17 19:35:30 -0400370
371 *timeout* can either be ``None`` or a float or int number of seconds
372 to wait for. If *timeout* is ``None``, block until the future
373 completes.
374
375 If a timeout occurs, it cancels the task and raises
376 :exc:`asyncio.TimeoutError`.
377
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700378 To avoid the task :meth:`cancellation <Task.cancel>`,
379 wrap it in :func:`shield`.
Yury Selivanov512d7102018-09-17 19:35:30 -0400380
381 The function will wait until the future is actually cancelled,
382 so the total wait time may exceed the *timeout*.
383
384 If the wait is cancelled, the future *fut* is also cancelled.
385
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700386 The *loop* argument is deprecated and scheduled for removal
387 in Python 4.0.
388
Yury Selivanov512d7102018-09-17 19:35:30 -0400389 .. _asyncio_example_waitfor:
390
391 Example::
392
393 async def eternity():
394 # Sleep for one hour
395 await asyncio.sleep(3600)
396 print('yay!')
397
398 async def main():
399 # Wait for at most 1 second
400 try:
401 await asyncio.wait_for(eternity(), timeout=1.0)
402 except asyncio.TimeoutError:
403 print('timeout!')
404
405 asyncio.run(main())
406
407 # Expected output:
408 #
409 # timeout!
410
411 .. versionchanged:: 3.7
412 When *fut* is cancelled due to a timeout, ``wait_for`` waits
413 for *fut* to be cancelled. Previously, it raised
414 :exc:`asyncio.TimeoutError` immediately.
415
416
417Waiting Primitives
418==================
419
420.. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200421 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100422
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700423 Run :ref:`awaitable objects <asyncio-awaitables>` in the *fs*
424 sequence concurrently and block until the condition specified
425 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100426
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700427 If any awaitable in *fs* is a coroutine, it is automatically
428 scheduled as a Task.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200429
Yury Selivanov512d7102018-09-17 19:35:30 -0400430 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100431
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700432 The *loop* argument is deprecated and scheduled for removal
433 in Python 4.0.
434
Yury Selivanov512d7102018-09-17 19:35:30 -0400435 *timeout* (a float or int), if specified, can be used to control
436 the maximum number of seconds to wait before returning.
437
438 Note that this function does not raise :exc:`asyncio.TimeoutError`.
439 Futures or Tasks that aren't done when the timeout occurs are simply
440 returned in the second set.
441
442 *return_when* indicates when this function should return. It must
443 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100444
445 .. tabularcolumns:: |l|L|
446
447 +-----------------------------+----------------------------------------+
448 | Constant | Description |
449 +=============================+========================================+
450 | :const:`FIRST_COMPLETED` | The function will return when any |
451 | | future finishes or is cancelled. |
452 +-----------------------------+----------------------------------------+
453 | :const:`FIRST_EXCEPTION` | The function will return when any |
454 | | future finishes by raising an |
455 | | exception. If no future raises an |
456 | | exception then it is equivalent to |
457 | | :const:`ALL_COMPLETED`. |
458 +-----------------------------+----------------------------------------+
459 | :const:`ALL_COMPLETED` | The function will return when all |
460 | | futures finish or are cancelled. |
461 +-----------------------------+----------------------------------------+
462
Yury Selivanov512d7102018-09-17 19:35:30 -0400463 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
464 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100465
466 Usage::
467
Andrew Svetlov88743422017-12-11 17:35:49 +0200468 done, pending = await asyncio.wait(fs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100469
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470
Yury Selivanov512d7102018-09-17 19:35:30 -0400471.. function:: as_completed(fs, \*, loop=None, timeout=None)
472
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700473 Run :ref:`awaitable objects <asyncio-awaitables>` in the *fs*
474 set concurrently. Return an iterator of :class:`Future` objects.
475 Each Future object returned represents the earliest result
476 from the set of the remaining awaitables.
Yury Selivanov512d7102018-09-17 19:35:30 -0400477
478 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
479 all Futures are done.
480
481 Example::
482
483 for f in as_completed(fs):
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700484 earliest_result = await f
Yury Selivanov512d7102018-09-17 19:35:30 -0400485 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100486
Victor Stinner3e09e322013-12-03 01:22:06 +0100487
Yury Selivanov512d7102018-09-17 19:35:30 -0400488Scheduling From Other Threads
489=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100490
Yury Selivanov512d7102018-09-17 19:35:30 -0400491.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100492
Yury Selivanov512d7102018-09-17 19:35:30 -0400493 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100494
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700495 Return a :class:`concurrent.futures.Future` to wait for the result
496 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100497
Yury Selivanov512d7102018-09-17 19:35:30 -0400498 This function is meant to be called from a different OS thread
499 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200500
Yury Selivanov512d7102018-09-17 19:35:30 -0400501 # Create a coroutine
502 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500503
Yury Selivanov512d7102018-09-17 19:35:30 -0400504 # Submit the coroutine to a given loop
505 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100506
Yury Selivanov512d7102018-09-17 19:35:30 -0400507 # Wait for the result with an optional timeout argument
508 assert future.result(timeout) == 3
509
510 If an exception is raised in the coroutine, the returned Future
511 will be notified. It can also be used to cancel the task in
512 the event loop::
513
514 try:
515 result = future.result(timeout)
516 except asyncio.TimeoutError:
517 print('The coroutine took too long, cancelling the task...')
518 future.cancel()
519 except Exception as exc:
520 print('The coroutine raised an exception: {!r}'.format(exc))
521 else:
522 print('The coroutine returned: {!r}'.format(result))
523
524 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
525 section of the documentation.
526
527 Unlike other asyncio functions this functions requires the *loop*
528 argument to be passed explicitly.
529
530 .. versionadded:: 3.5.1
531
532
533Introspection
534=============
535
536
537.. function:: current_task(loop=None)
538
539 Return the currently running :class:`Task` instance, or ``None`` if
540 no task is running.
541
542 If *loop* is ``None`` :func:`get_running_loop` is used to get
543 the current loop.
544
545 .. versionadded:: 3.7
546
547
548.. function:: all_tasks(loop=None)
549
550 Return a set of not yet finished :class:`Task` objects run by
551 the loop.
552
553 If *loop* is ``None``, :func:`get_running_loop` is used for getting
554 current loop.
555
556 .. versionadded:: 3.7
557
558
559Task Object
560===========
561
562.. class:: Task(coro, \*, loop=None)
563
564 A :class:`Future`-like object that wraps a Python
565 :ref:`coroutine <coroutine>`. Not thread-safe.
566
567 Tasks are used to run coroutines in event loops.
568 If a coroutine awaits on a Future, the Task suspends
569 the execution of the coroutine and waits for the completion
570 of the Future. When the Future is *done*, the execution of
571 the wrapped coroutine resumes.
572
573 Event loops use cooperative scheduling: an event loop runs
574 one Task at a time. While a Task awaits for the completion of a
575 Future, the event loop runs other Tasks, callbacks, or performs
576 IO operations.
577
578 Use the high-level :func:`asyncio.create_task` function to create
579 Tasks, or the low-level :meth:`loop.create_task` or
580 :func:`ensure_future` functions. Manual instantiation of Tasks
581 is discouraged.
582
583 To cancel a running Task use the :meth:`cancel` method. Calling it
584 will cause the Task to throw a :exc:`CancelledError` exception into
585 the wrapped coroutine. If a coroutine is awaiting on a Future
586 object during cancellation, the Future object will be cancelled.
587
588 :meth:`cancelled` can be used to check if the Task was cancelled.
589 The method returns ``True`` if the wrapped coroutine did not
590 suppress the :exc:`CancelledError` exception and was actually
591 cancelled.
592
593 :class:`asyncio.Task` inherits from :class:`Future` all of its
594 APIs except :meth:`Future.set_result` and
595 :meth:`Future.set_exception`.
596
597 Tasks support the :mod:`contextvars` module. When a Task
598 is created it copies the current context and later runs its
599 coroutine in the copied context.
Miss Islington (bot)d8948c52018-05-29 15:37:06 -0700600
601 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400602 Added support for the :mod:`contextvars` module.
603
604 .. method:: cancel()
605
606 Request the Task to be cancelled.
607
608 This arranges for a :exc:`CancelledError` exception to be thrown
609 into the wrapped coroutine on the next cycle of the event loop.
610
611 The coroutine then has a chance to clean up or even deny the
612 request by suppressing the exception with a :keyword:`try` ...
613 ... ``except CancelledError`` ... :keyword:`finally` block.
614 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
615 not guarantee that the Task will be cancelled, although
616 suppressing cancellation completely is not common and is actively
617 discouraged.
618
619 .. _asyncio_example_task_cancel:
620
621 The following example illustrates how coroutines can intercept
622 the cancellation request::
623
624 async def cancel_me():
625 print('cancel_me(): before sleep')
626
627 try:
628 # Wait for 1 hour
629 await asyncio.sleep(3600)
630 except asyncio.CancelledError:
631 print('cancel_me(): cancel sleep')
632 raise
633 finally:
634 print('cancel_me(): after sleep')
635
636 async def main():
637 # Create a "cancel_me" Task
638 task = asyncio.create_task(cancel_me())
639
640 # Wait for 1 second
641 await asyncio.sleep(1)
642
643 task.cancel()
644 try:
645 await task
646 except asyncio.CancelledError:
647 print("main(): cancel_me is cancelled now")
648
649 asyncio.run(main())
650
651 # Expected output:
652 #
653 # cancel_me(): before sleep
654 # cancel_me(): cancel sleep
655 # cancel_me(): after sleep
656 # main(): cancel_me is cancelled now
657
658 .. method:: cancelled()
659
660 Return ``True`` if the Task is *cancelled*.
661
662 The Task is *cancelled* when the cancellation was requested with
663 :meth:`cancel` and the wrapped coroutine propagated the
664 :exc:`CancelledError` exception thrown into it.
665
666 .. method:: done()
667
668 Return ``True`` if the Task is *done*.
669
670 A Task is *done* when the wrapped coroutine either returned
671 a value, raised an exception, or the Task was cancelled.
672
673 .. method:: get_stack(\*, limit=None)
674
675 Return the list of stack frames for this Task.
676
677 If the wrapped coroutine is not done, this returns the stack
678 where it is suspended. If the coroutine has completed
679 successfully or was cancelled, this returns an empty list.
680 If the coroutine was terminated by an exception, this returns
681 the list of traceback frames.
682
683 The frames are always ordered from oldest to newest.
684
685 Only one stack frame is returned for a suspended coroutine.
686
687 The optional *limit* argument sets the maximum number of frames
688 to return; by default all available frames are returned.
689 The ordering of the returned list differs depending on whether
690 a stack or a traceback is returned: the newest frames of a
691 stack are returned, but the oldest frames of a traceback are
692 returned. (This matches the behavior of the traceback module.)
693
694 .. method:: print_stack(\*, limit=None, file=None)
695
696 Print the stack or traceback for this Task.
697
698 This produces output similar to that of the traceback module
699 for the frames retrieved by :meth:`get_stack`.
700
701 The *limit* argument is passed to :meth:`get_stack` directly.
702
703 The *file* argument is an I/O stream to which the output
704 is written; by default output is written to :data:`sys.stderr`.
705
706 .. classmethod:: all_tasks(loop=None)
707
708 Return a set of all tasks for an event loop.
709
710 By default all tasks for the current event loop are returned.
711 If *loop* is ``None``, the :func:`get_event_loop` function
712 is used to get the current loop.
713
714 This method is **deprecated** and will be removed in
715 Python 3.9. Use the :func:`all_tasks` function instead.
716
717 .. classmethod:: current_task(loop=None)
718
719 Return the currently running task or ``None``.
720
721 If *loop* is ``None``, the :func:`get_event_loop` function
722 is used to get the current loop.
723
724 This method is **deprecated** and will be removed in
725 Python 3.9. Use the :func:`current_task` function instead.
726
727
728.. _asyncio_generator_based_coro:
729
730Generator-based Coroutines
731==========================
732
733.. note::
734
735 Support for generator-based coroutines is **deprecated** and
736 is scheduled for removal in Python 4.0.
737
738Generator-based coroutines predate async/await syntax. They are
739Python generators that use ``yield from`` expressions to await
740on Futures and other coroutines.
741
742Generator-based coroutines should be decorated with
743:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
744enforced.
745
746
747.. decorator:: coroutine
748
749 Decorator to mark generator-based coroutines.
750
751 This decorator enables legacy generator-based coroutines to be
752 compatible with async/await code::
753
754 @asyncio.coroutine
755 def old_style_coroutine():
756 yield from asyncio.sleep(1)
757
758 async def main():
759 await old_style_coroutine()
760
761 This decorator is **deprecated** and is scheduled for removal in
762 Python 4.0.
763
764 This decorator should not be used for :keyword:`async def`
765 coroutines.
766
767.. function:: iscoroutine(obj)
768
769 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
770
771 This method is different from :func:`inspect.iscoroutine` because
772 it returns ``True`` for generator-based coroutines decorated with
773 :func:`@coroutine <coroutine>`.
774
775.. function:: iscoroutinefunction(func)
776
777 Return ``True`` if *func* is a :ref:`coroutine function
778 <coroutine>`.
779
780 This method is different from :func:`inspect.iscoroutinefunction`
781 because it returns ``True`` for generator-based coroutine functions
782 decorated with :func:`@coroutine <coroutine>`.