2013-12-20 15:37:39 -04:00
|
|
|
.. currentmodule:: asyncio
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
Tasks and coroutines
|
|
|
|
====================
|
|
|
|
|
|
|
|
.. _coroutine:
|
|
|
|
|
|
|
|
Coroutines
|
|
|
|
----------
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
Coroutines used with :mod:`asyncio` may be implemented using the
|
|
|
|
:keyword:`async def` statement, or by using :term:`generators <generator>`.
|
|
|
|
The :keyword:`async def` type of coroutine was added in Python 3.5, and
|
|
|
|
is recommended if there is no need to support older Python versions.
|
|
|
|
|
|
|
|
Generator-based coroutines should be decorated with :func:`@asyncio.coroutine
|
|
|
|
<asyncio.coroutine>`, although this is not strictly enforced.
|
|
|
|
The decorator enables compatibility with :keyword:`async def` coroutines,
|
|
|
|
and also serves as documentation. Generator-based
|
|
|
|
coroutines use the ``yield from`` syntax introduced in :pep:`380`,
|
2013-12-02 20:08:00 -04:00
|
|
|
instead of the original ``yield`` syntax.
|
|
|
|
|
|
|
|
The word "coroutine", like the word "generator", is used for two
|
|
|
|
different (though related) concepts:
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
- The function that defines a coroutine
|
|
|
|
(a function definition using :keyword:`async def` or
|
2014-01-16 14:30:21 -04:00
|
|
|
decorated with ``@asyncio.coroutine``). If disambiguation is needed
|
2014-01-29 19:18:50 -04:00
|
|
|
we will call this a *coroutine function* (:func:`iscoroutinefunction`
|
|
|
|
returns ``True``).
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
- The object obtained by calling a coroutine function. This object
|
|
|
|
represents a computation or an I/O operation (usually a combination)
|
|
|
|
that will complete eventually. If disambiguation is needed we will
|
2014-01-29 19:18:50 -04:00
|
|
|
call it a *coroutine object* (:func:`iscoroutine` returns ``True``).
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
Things a coroutine can do:
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
- ``result = await future`` or ``result = yield from future`` --
|
|
|
|
suspends the coroutine until the
|
2013-12-02 20:08:00 -04:00
|
|
|
future is done, then returns the future's result, or raises an
|
|
|
|
exception, which will be propagated. (If the future is cancelled,
|
|
|
|
it will raise a ``CancelledError`` exception.) Note that tasks are
|
|
|
|
futures, and everything said about futures also applies to tasks.
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
- ``result = await coroutine`` or ``result = yield from coroutine`` --
|
|
|
|
wait for another coroutine to
|
2013-12-02 20:08:00 -04:00
|
|
|
produce a result (or raise an exception, which will be propagated).
|
|
|
|
The ``coroutine`` expression must be a *call* to another coroutine.
|
|
|
|
|
|
|
|
- ``return expression`` -- produce a result to the coroutine that is
|
2015-06-24 12:04:15 -03:00
|
|
|
waiting for this one using :keyword:`await` or ``yield from``.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
- ``raise exception`` -- raise an exception in the coroutine that is
|
2015-06-24 12:04:15 -03:00
|
|
|
waiting for this one using :keyword:`await` or ``yield from``.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
Calling a coroutine does not start its code running --
|
|
|
|
the coroutine object returned by the call doesn't do anything until you
|
|
|
|
schedule its execution. There are two basic ways to start it running:
|
|
|
|
call ``await coroutine`` or ``yield from coroutine`` from another coroutine
|
2014-07-08 07:39:10 -03:00
|
|
|
(assuming the other coroutine is already running!), or schedule its execution
|
2016-08-08 13:41:21 -03:00
|
|
|
using the :func:`ensure_future` function or the :meth:`AbstractEventLoop.create_task`
|
2014-08-10 20:11:13 -03:00
|
|
|
method.
|
|
|
|
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
Coroutines (and tasks) can only run when the event loop is running.
|
|
|
|
|
2014-01-16 13:58:01 -04:00
|
|
|
.. decorator:: coroutine
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
Decorator to mark generator-based coroutines. This enables
|
|
|
|
the generator use :keyword:`!yield from` to call :keyword:`async
|
|
|
|
def` coroutines, and also enables the generator to be called by
|
|
|
|
:keyword:`async def` coroutines, for instance using an
|
|
|
|
:keyword:`await` expression.
|
|
|
|
|
|
|
|
There is no need to decorate :keyword:`async def` coroutines themselves.
|
2014-01-16 13:58:01 -04:00
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
If the generator is not yielded from before it is destroyed, an error
|
2014-01-16 13:58:01 -04:00
|
|
|
message is logged. See :ref:`Detect coroutines never scheduled
|
|
|
|
<asyncio-coroutine-not-scheduled>`.
|
|
|
|
|
2014-02-20 17:20:44 -04:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
In this documentation, some methods are documented as coroutines,
|
|
|
|
even if they are plain Python functions returning a :class:`Future`.
|
|
|
|
This is intentional to have a freedom of tweaking the implementation
|
|
|
|
of these functions in the future. If such a function is needed to be
|
2015-06-30 23:13:22 -03:00
|
|
|
used in a callback-style code, wrap its result with :func:`ensure_future`.
|
2014-02-20 17:20:44 -04:00
|
|
|
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2013-12-09 21:09:46 -04:00
|
|
|
.. _asyncio-hello-world-coroutine:
|
|
|
|
|
2014-10-15 13:49:16 -03:00
|
|
|
Example: Hello World coroutine
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
2013-12-09 21:09:46 -04:00
|
|
|
|
2014-10-15 13:49:16 -03:00
|
|
|
Example of coroutine displaying ``"Hello World"``::
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
async def hello_world():
|
2014-10-15 13:49:16 -03:00
|
|
|
print("Hello World!")
|
|
|
|
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
# Blocking call which returns when the hello_world() coroutine is done
|
|
|
|
loop.run_until_complete(hello_world())
|
|
|
|
loop.close()
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>`
|
2016-08-08 13:41:21 -03:00
|
|
|
example uses the :meth:`AbstractEventLoop.call_soon` method to schedule a
|
2014-10-15 13:49:16 -03:00
|
|
|
callback.
|
|
|
|
|
|
|
|
|
|
|
|
.. _asyncio-date-coroutine:
|
|
|
|
|
|
|
|
Example: Coroutine displaying the current date
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
Example of coroutine displaying the current date every second during 5 seconds
|
|
|
|
using the :meth:`sleep` function::
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
import datetime
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
async def display_date(loop):
|
2014-10-15 13:49:16 -03:00
|
|
|
end_time = loop.time() + 5.0
|
2013-12-09 21:09:46 -04:00
|
|
|
while True:
|
2014-10-15 13:49:16 -03:00
|
|
|
print(datetime.datetime.now())
|
|
|
|
if (loop.time() + 1.0) >= end_time:
|
|
|
|
break
|
2015-06-24 12:04:15 -03:00
|
|
|
await asyncio.sleep(1)
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
loop = asyncio.get_event_loop()
|
2014-10-15 13:49:16 -03:00
|
|
|
# Blocking call which returns when the display_date() coroutine is done
|
|
|
|
loop.run_until_complete(display_date(loop))
|
|
|
|
loop.close()
|
2013-12-09 21:09:46 -04:00
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
The same coroutine implemented using a generator::
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def display_date(loop):
|
|
|
|
end_time = loop.time() + 5.0
|
|
|
|
while True:
|
|
|
|
print(datetime.datetime.now())
|
|
|
|
if (loop.time() + 1.0) >= end_time:
|
|
|
|
break
|
|
|
|
yield from asyncio.sleep(1)
|
|
|
|
|
2013-12-09 21:09:46 -04:00
|
|
|
.. seealso::
|
|
|
|
|
2014-10-15 13:49:16 -03:00
|
|
|
The :ref:`display the current date with call_later()
|
|
|
|
<asyncio-date-callback>` example uses a callback with the
|
2016-08-08 13:41:21 -03:00
|
|
|
:meth:`AbstractEventLoop.call_later` method.
|
2014-10-15 13:49:16 -03:00
|
|
|
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
Example: Chain coroutines
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
Example chaining coroutines::
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
async def compute(x, y):
|
2013-12-09 21:09:46 -04:00
|
|
|
print("Compute %s + %s ..." % (x, y))
|
2015-06-24 12:04:15 -03:00
|
|
|
await asyncio.sleep(1.0)
|
2013-12-09 21:09:46 -04:00
|
|
|
return x + y
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
async def print_sum(x, y):
|
|
|
|
result = await compute(x, y)
|
2013-12-09 21:09:46 -04:00
|
|
|
print("%s + %s = %s" % (x, y, result))
|
|
|
|
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
loop.run_until_complete(print_sum(1, 2))
|
2014-01-28 18:32:40 -04:00
|
|
|
loop.close()
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
|
2014-02-08 20:36:14 -04:00
|
|
|
until ``compute()`` is completed before returning its result.
|
2013-12-09 21:09:46 -04:00
|
|
|
|
2013-12-12 07:35:17 -04:00
|
|
|
Sequence diagram of the example:
|
|
|
|
|
|
|
|
.. image:: tulip_coro.png
|
|
|
|
:align: center
|
|
|
|
|
2016-08-08 13:41:21 -03:00
|
|
|
The "Task" is created by the :meth:`AbstractEventLoop.run_until_complete` method
|
2014-01-16 14:30:21 -04:00
|
|
|
when it gets a coroutine object instead of a task.
|
2013-12-13 07:51:24 -04:00
|
|
|
|
|
|
|
The diagram shows the control flow, it does not describe exactly how things
|
|
|
|
work internally. For example, the sleep coroutine creates an internal future
|
2016-08-08 13:41:21 -03:00
|
|
|
which uses :meth:`AbstractEventLoop.call_later` to wake up the task in 1 second.
|
2013-12-12 07:35:17 -04:00
|
|
|
|
2013-12-09 21:09:46 -04:00
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
InvalidStateError
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
.. exception:: InvalidStateError
|
|
|
|
|
|
|
|
The operation is not allowed in this state.
|
|
|
|
|
|
|
|
|
2014-05-28 19:04:57 -03:00
|
|
|
TimeoutError
|
|
|
|
------------
|
|
|
|
|
|
|
|
.. exception:: TimeoutError
|
|
|
|
|
|
|
|
The operation exceeded the given deadline.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
This exception is different from the builtin :exc:`TimeoutError` exception!
|
|
|
|
|
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
Future
|
|
|
|
------
|
|
|
|
|
|
|
|
.. class:: Future(\*, loop=None)
|
|
|
|
|
|
|
|
This class is *almost* compatible with :class:`concurrent.futures.Future`.
|
|
|
|
|
|
|
|
Differences:
|
|
|
|
|
|
|
|
- :meth:`result` and :meth:`exception` do not take a timeout argument and
|
|
|
|
raise an exception when the future isn't done yet.
|
|
|
|
|
|
|
|
- Callbacks registered with :meth:`add_done_callback` are always called
|
2016-08-08 13:41:21 -03:00
|
|
|
via the event loop's :meth:`~AbstractEventLoop.call_soon_threadsafe`.
|
2013-12-03 14:17:25 -04:00
|
|
|
|
|
|
|
- This class is not compatible with the :func:`~concurrent.futures.wait` and
|
|
|
|
:func:`~concurrent.futures.as_completed` functions in the
|
|
|
|
:mod:`concurrent.futures` package.
|
|
|
|
|
2015-02-25 09:24:15 -04:00
|
|
|
This class is :ref:`not thread safe <asyncio-multithreading>`.
|
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
.. method:: cancel()
|
|
|
|
|
|
|
|
Cancel the future and schedule callbacks.
|
|
|
|
|
|
|
|
If the future is already done or cancelled, return ``False``. Otherwise,
|
|
|
|
change the future's state to cancelled, schedule the callbacks and return
|
|
|
|
``True``.
|
|
|
|
|
|
|
|
.. method:: cancelled()
|
|
|
|
|
|
|
|
Return ``True`` if the future was cancelled.
|
|
|
|
|
|
|
|
.. method:: done()
|
|
|
|
|
|
|
|
Return True if the future is done.
|
|
|
|
|
|
|
|
Done means either that a result / exception are available, or that the
|
|
|
|
future was cancelled.
|
|
|
|
|
|
|
|
.. method:: result()
|
|
|
|
|
|
|
|
Return the result this future represents.
|
|
|
|
|
|
|
|
If the future has been cancelled, raises :exc:`CancelledError`. If the
|
|
|
|
future's result isn't yet available, raises :exc:`InvalidStateError`. If
|
|
|
|
the future is done and has an exception set, this exception is raised.
|
|
|
|
|
|
|
|
.. method:: exception()
|
|
|
|
|
|
|
|
Return the exception that was set on this future.
|
|
|
|
|
|
|
|
The exception (or ``None`` if no exception was set) is returned only if
|
|
|
|
the future is done. If the future has been cancelled, raises
|
|
|
|
:exc:`CancelledError`. If the future isn't done yet, raises
|
|
|
|
:exc:`InvalidStateError`.
|
|
|
|
|
|
|
|
.. method:: add_done_callback(fn)
|
|
|
|
|
|
|
|
Add a callback to be run when the future becomes done.
|
|
|
|
|
|
|
|
The callback is called with a single argument - the future object. If the
|
|
|
|
future is already done when this is called, the callback is scheduled
|
2016-08-08 13:41:21 -03:00
|
|
|
with :meth:`~AbstractEventLoop.call_soon`.
|
2013-12-03 14:17:25 -04:00
|
|
|
|
2014-11-28 08:15:41 -04:00
|
|
|
:ref:`Use functools.partial to pass parameters to the callback
|
|
|
|
<asyncio-pass-keywords>`. For example,
|
|
|
|
``fut.add_done_callback(functools.partial(print, "Future:",
|
|
|
|
flush=True))`` will call ``print("Future:", fut, flush=True)``.
|
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
.. method:: remove_done_callback(fn)
|
|
|
|
|
|
|
|
Remove all instances of a callback from the "call when done" list.
|
|
|
|
|
|
|
|
Returns the number of callbacks removed.
|
|
|
|
|
|
|
|
.. method:: set_result(result)
|
|
|
|
|
|
|
|
Mark the future done and set its result.
|
|
|
|
|
|
|
|
If the future is already done when this method is called, raises
|
|
|
|
:exc:`InvalidStateError`.
|
|
|
|
|
|
|
|
.. method:: set_exception(exception)
|
|
|
|
|
|
|
|
Mark the future done and set an exception.
|
|
|
|
|
|
|
|
If the future is already done when this method is called, raises
|
|
|
|
:exc:`InvalidStateError`.
|
|
|
|
|
|
|
|
|
2013-12-09 21:09:46 -04:00
|
|
|
Example: Future with run_until_complete()
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
2014-01-16 14:30:21 -04:00
|
|
|
Example combining a :class:`Future` and a :ref:`coroutine function
|
|
|
|
<coroutine>`::
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def slow_operation(future):
|
|
|
|
yield from asyncio.sleep(1)
|
2014-02-17 05:54:30 -04:00
|
|
|
future.set_result('Future is done!')
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
future = asyncio.Future()
|
2015-05-11 17:33:41 -03:00
|
|
|
asyncio.ensure_future(slow_operation(future))
|
2013-12-09 21:09:46 -04:00
|
|
|
loop.run_until_complete(future)
|
|
|
|
print(future.result())
|
2014-01-28 18:32:40 -04:00
|
|
|
loop.close()
|
2013-12-09 21:09:46 -04:00
|
|
|
|
2014-07-24 03:33:14 -03:00
|
|
|
The coroutine function is responsible for the computation (which takes 1 second)
|
2014-01-16 14:30:21 -04:00
|
|
|
and it stores the result into the future. The
|
2016-08-08 13:41:21 -03:00
|
|
|
:meth:`~AbstractEventLoop.run_until_complete` method waits for the completion of
|
2013-12-09 21:09:46 -04:00
|
|
|
the future.
|
|
|
|
|
|
|
|
.. note::
|
2016-08-08 13:41:21 -03:00
|
|
|
The :meth:`~AbstractEventLoop.run_until_complete` method uses internally the
|
2013-12-09 21:09:46 -04:00
|
|
|
:meth:`~Future.add_done_callback` method to be notified when the future is
|
|
|
|
done.
|
|
|
|
|
|
|
|
|
|
|
|
Example: Future with run_forever()
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
The previous example can be written differently using the
|
|
|
|
:meth:`Future.add_done_callback` method to describe explicitly the control
|
|
|
|
flow::
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def slow_operation(future):
|
|
|
|
yield from asyncio.sleep(1)
|
2014-02-17 05:54:30 -04:00
|
|
|
future.set_result('Future is done!')
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
def got_result(future):
|
|
|
|
print(future.result())
|
|
|
|
loop.stop()
|
|
|
|
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
future = asyncio.Future()
|
2015-05-11 17:33:41 -03:00
|
|
|
asyncio.ensure_future(slow_operation(future))
|
2013-12-09 21:09:46 -04:00
|
|
|
future.add_done_callback(got_result)
|
2014-02-17 05:54:30 -04:00
|
|
|
try:
|
|
|
|
loop.run_forever()
|
|
|
|
finally:
|
|
|
|
loop.close()
|
2013-12-09 21:09:46 -04:00
|
|
|
|
2014-12-02 12:52:45 -04:00
|
|
|
In this example, the future is used to link ``slow_operation()`` to
|
|
|
|
``got_result()``: when ``slow_operation()`` is done, ``got_result()`` is called
|
|
|
|
with the result.
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
|
2013-12-02 20:08:00 -04:00
|
|
|
Task
|
|
|
|
----
|
|
|
|
|
|
|
|
.. class:: Task(coro, \*, loop=None)
|
|
|
|
|
2014-07-08 07:39:10 -03:00
|
|
|
Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a
|
|
|
|
future. A task is a subclass of :class:`Future`.
|
|
|
|
|
2014-09-24 12:09:09 -03:00
|
|
|
A task is responsible for executing a coroutine object in an event loop. If
|
2014-07-08 07:39:10 -03:00
|
|
|
the wrapped coroutine yields from a future, the task suspends the execution
|
2016-10-04 14:45:47 -03:00
|
|
|
of the wrapped coroutine and waits for the completion of the future. When
|
2014-07-08 07:39:10 -03:00
|
|
|
the future is done, the execution of the wrapped coroutine restarts with the
|
|
|
|
result or the exception of the future.
|
|
|
|
|
|
|
|
Event loops use cooperative scheduling: an event loop only runs one task at
|
2014-09-24 12:09:09 -03:00
|
|
|
a time. Other tasks may run in parallel if other event loops are
|
2014-07-08 07:39:10 -03:00
|
|
|
running in different threads. While a task waits for the completion of a
|
|
|
|
future, the event loop executes a new task.
|
|
|
|
|
2016-01-11 08:40:35 -04:00
|
|
|
The cancellation of a task is different from the cancelation of a
|
|
|
|
future. Calling :meth:`cancel` will throw a
|
|
|
|
:exc:`~concurrent.futures.CancelledError` to the wrapped
|
|
|
|
coroutine. :meth:`~Future.cancelled` only returns ``True`` if the
|
2014-07-08 07:39:10 -03:00
|
|
|
wrapped coroutine did not catch the
|
|
|
|
:exc:`~concurrent.futures.CancelledError` exception, or raised a
|
|
|
|
:exc:`~concurrent.futures.CancelledError` exception.
|
|
|
|
|
|
|
|
If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
|
|
|
|
<coroutine>` did not complete. It is probably a bug and a warning is
|
|
|
|
logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
|
|
|
|
|
2015-06-30 23:13:22 -03:00
|
|
|
Don't directly create :class:`Task` instances: use the :func:`ensure_future`
|
2016-08-08 13:41:21 -03:00
|
|
|
function or the :meth:`AbstractEventLoop.create_task` method.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2015-02-25 09:24:15 -04:00
|
|
|
This class is :ref:`not thread safe <asyncio-multithreading>`.
|
|
|
|
|
2013-12-02 20:08:00 -04:00
|
|
|
.. classmethod:: all_tasks(loop=None)
|
|
|
|
|
|
|
|
Return a set of all tasks for an event loop.
|
|
|
|
|
|
|
|
By default all tasks for the current event loop are returned.
|
|
|
|
|
2013-12-10 07:14:50 -04:00
|
|
|
.. classmethod:: current_task(loop=None)
|
|
|
|
|
|
|
|
Return the currently running task in an event loop or ``None``.
|
|
|
|
|
|
|
|
By default the current task for the current event loop is returned.
|
|
|
|
|
|
|
|
``None`` is returned when called not in the context of a :class:`Task`.
|
|
|
|
|
2014-06-02 18:06:46 -03:00
|
|
|
.. method:: cancel()
|
|
|
|
|
2014-09-24 12:09:09 -03:00
|
|
|
Request that this task cancel itself.
|
2014-06-02 18:06:46 -03:00
|
|
|
|
|
|
|
This arranges for a :exc:`~concurrent.futures.CancelledError` to be
|
|
|
|
thrown into the wrapped coroutine on the next cycle through the event
|
|
|
|
loop. The coroutine then has a chance to clean up or even deny the
|
|
|
|
request using try/except/finally.
|
|
|
|
|
2014-09-24 12:09:09 -03:00
|
|
|
Unlike :meth:`Future.cancel`, this does not guarantee that the task
|
2014-06-02 18:06:46 -03:00
|
|
|
will be cancelled: the exception might be caught and acted upon, delaying
|
2014-09-24 12:09:09 -03:00
|
|
|
cancellation of the task or preventing cancellation completely. The task
|
|
|
|
may also return a value or raise a different exception.
|
2014-06-02 18:06:46 -03:00
|
|
|
|
|
|
|
Immediately after this method is called, :meth:`~Future.cancelled` will
|
|
|
|
not return ``True`` (unless the task was already cancelled). A task will
|
|
|
|
be marked as cancelled when the wrapped coroutine terminates with a
|
|
|
|
:exc:`~concurrent.futures.CancelledError` exception (even if
|
|
|
|
:meth:`cancel` was not called).
|
|
|
|
|
|
|
|
.. method:: get_stack(\*, limit=None)
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
Return the list of stack frames for this task's coroutine.
|
|
|
|
|
2016-01-11 08:40:35 -04:00
|
|
|
If the coroutine is not done, this returns the stack where it is
|
|
|
|
suspended. If the coroutine has completed successfully or was
|
|
|
|
cancelled, this returns an empty list. If the coroutine was
|
|
|
|
terminated by an exception, this returns the list of traceback
|
|
|
|
frames.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
The frames are always ordered from oldest to newest.
|
|
|
|
|
2014-02-08 20:36:14 -04:00
|
|
|
The optional limit gives the maximum number of frames to return; by
|
2013-12-02 20:08:00 -04:00
|
|
|
default all available frames are returned. Its meaning differs depending
|
|
|
|
on whether a stack or a traceback is returned: the newest frames of a
|
|
|
|
stack are returned, but the oldest frames of a traceback are returned.
|
|
|
|
(This matches the behavior of the traceback module.)
|
|
|
|
|
|
|
|
For reasons beyond our control, only one stack frame is returned for a
|
|
|
|
suspended coroutine.
|
|
|
|
|
|
|
|
.. method:: print_stack(\*, limit=None, file=None)
|
|
|
|
|
|
|
|
Print the stack or traceback for this task's coroutine.
|
|
|
|
|
|
|
|
This produces output similar to that of the traceback module, for the
|
|
|
|
frames retrieved by get_stack(). The limit argument is passed to
|
|
|
|
get_stack(). The file argument is an I/O stream to which the output
|
2014-09-24 12:09:09 -03:00
|
|
|
is written; by default output is written to sys.stderr.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
|
2013-12-09 21:09:46 -04:00
|
|
|
Example: Parallel execution of tasks
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
Example executing 3 tasks (A, B, C) in parallel::
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
2013-12-09 21:51:05 -04:00
|
|
|
def factorial(name, number):
|
2013-12-09 21:09:46 -04:00
|
|
|
f = 1
|
2013-12-09 21:51:05 -04:00
|
|
|
for i in range(2, number+1):
|
|
|
|
print("Task %s: Compute factorial(%s)..." % (name, i))
|
2013-12-09 21:09:46 -04:00
|
|
|
yield from asyncio.sleep(1)
|
2013-12-09 21:51:05 -04:00
|
|
|
f *= i
|
|
|
|
print("Task %s: factorial(%s) = %s" % (name, number, f))
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
loop = asyncio.get_event_loop()
|
2014-07-08 07:39:10 -03:00
|
|
|
tasks = [
|
2015-05-11 17:33:41 -03:00
|
|
|
asyncio.ensure_future(factorial("A", 2)),
|
|
|
|
asyncio.ensure_future(factorial("B", 3)),
|
|
|
|
asyncio.ensure_future(factorial("C", 4))]
|
2016-08-07 21:10:39 -03:00
|
|
|
loop.run_until_complete(asyncio.gather(*tasks))
|
2014-01-28 18:32:40 -04:00
|
|
|
loop.close()
|
2013-12-09 21:09:46 -04:00
|
|
|
|
|
|
|
Output::
|
|
|
|
|
2013-12-09 21:51:05 -04:00
|
|
|
Task A: Compute factorial(2)...
|
|
|
|
Task B: Compute factorial(2)...
|
|
|
|
Task C: Compute factorial(2)...
|
|
|
|
Task A: factorial(2) = 2
|
|
|
|
Task B: Compute factorial(3)...
|
|
|
|
Task C: Compute factorial(3)...
|
|
|
|
Task B: factorial(3) = 6
|
|
|
|
Task C: Compute factorial(4)...
|
|
|
|
Task C: factorial(4) = 24
|
|
|
|
|
|
|
|
A task is automatically scheduled for execution when it is created. The event
|
2013-12-09 21:09:46 -04:00
|
|
|
loop stops when all tasks are done.
|
|
|
|
|
|
|
|
|
2013-12-02 20:08:00 -04:00
|
|
|
Task functions
|
|
|
|
--------------
|
|
|
|
|
2014-01-20 11:02:22 -04:00
|
|
|
.. note::
|
|
|
|
|
2016-02-10 01:44:01 -04:00
|
|
|
In the functions below, the optional *loop* argument allows explicitly setting
|
2014-01-20 11:02:22 -04:00
|
|
|
the event loop object used by the underlying task or coroutine. If it's
|
|
|
|
not provided, the default event loop is used.
|
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
.. function:: as_completed(fs, \*, loop=None, timeout=None)
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
Return an iterator whose values, when waited for, are :class:`Future`
|
|
|
|
instances.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2014-05-28 19:04:57 -03:00
|
|
|
Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures
|
|
|
|
are done.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
for f in as_completed(fs):
|
|
|
|
result = yield from f # The 'yield from' may raise
|
|
|
|
# Use result
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
The futures ``f`` are not necessarily members of fs.
|
|
|
|
|
2015-05-11 17:33:41 -03:00
|
|
|
.. function:: ensure_future(coro_or_future, \*, loop=None)
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2014-10-12 16:36:17 -03:00
|
|
|
Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
|
|
|
|
a future. Return a :class:`Task` object.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
If the argument is a :class:`Future`, it is returned directly.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2015-05-11 17:33:41 -03:00
|
|
|
.. versionadded:: 3.4.4
|
|
|
|
|
2015-12-15 01:45:24 -04:00
|
|
|
.. versionchanged:: 3.5.1
|
|
|
|
The function accepts any :term:`awaitable` object.
|
|
|
|
|
2014-08-10 20:11:13 -03:00
|
|
|
.. seealso::
|
|
|
|
|
2016-08-08 13:41:21 -03:00
|
|
|
The :meth:`AbstractEventLoop.create_task` method.
|
2014-08-10 20:11:13 -03:00
|
|
|
|
2015-05-11 17:33:41 -03:00
|
|
|
.. function:: async(coro_or_future, \*, loop=None)
|
|
|
|
|
|
|
|
A deprecated alias to :func:`ensure_future`.
|
|
|
|
|
|
|
|
.. deprecated:: 3.4.4
|
|
|
|
|
2013-12-03 14:17:25 -04:00
|
|
|
.. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False)
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2014-01-16 14:30:21 -04:00
|
|
|
Return a future aggregating results from the given coroutine objects or
|
|
|
|
futures.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
All futures must share the same event loop. If all the tasks are done
|
|
|
|
successfully, the returned future's result is the list of results (in the
|
|
|
|
order of the original sequence, not necessarily the order of results
|
2014-02-08 20:35:24 -04:00
|
|
|
arrival). If *return_exceptions* is True, exceptions in the tasks are
|
2013-12-02 20:08:00 -04:00
|
|
|
treated the same as successful results, and gathered in the result list;
|
|
|
|
otherwise, the first raised exception will be immediately propagated to the
|
|
|
|
returned future.
|
|
|
|
|
|
|
|
Cancellation: if the outer Future is cancelled, all children (that have not
|
|
|
|
completed yet) are also cancelled. If any child is cancelled, this is
|
|
|
|
treated as if it raised :exc:`~concurrent.futures.CancelledError` -- the
|
|
|
|
outer Future is *not* cancelled in this case. (This is to prevent the
|
|
|
|
cancellation of one child to cause other children to be cancelled.)
|
|
|
|
|
2014-01-29 19:18:50 -04:00
|
|
|
.. function:: iscoroutine(obj)
|
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`,
|
|
|
|
which may be based on a generator or an :keyword:`async def` coroutine.
|
2014-01-29 19:18:50 -04:00
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
.. function:: iscoroutinefunction(func)
|
2014-01-29 19:18:50 -04:00
|
|
|
|
2015-06-24 12:04:15 -03:00
|
|
|
Return ``True`` if *func* is determined to be a :ref:`coroutine function
|
|
|
|
<coroutine>`, which may be a decorated generator function or an
|
|
|
|
:keyword:`async def` function.
|
2014-01-29 19:18:50 -04:00
|
|
|
|
2016-01-11 08:40:35 -04:00
|
|
|
.. function:: run_coroutine_threadsafe(coro, loop)
|
|
|
|
|
|
|
|
Submit a :ref:`coroutine object <coroutine>` to a given event loop.
|
|
|
|
|
|
|
|
Return a :class:`concurrent.futures.Future` to access the result.
|
|
|
|
|
|
|
|
This function is meant to be called from a different thread than the one
|
|
|
|
where the event loop is running. Usage::
|
|
|
|
|
|
|
|
# Create a coroutine
|
|
|
|
coro = asyncio.sleep(1, result=3)
|
|
|
|
# Submit the coroutine to a given loop
|
|
|
|
future = asyncio.run_coroutine_threadsafe(coro, loop)
|
|
|
|
# Wait for the result with an optional timeout argument
|
|
|
|
assert future.result(timeout) == 3
|
|
|
|
|
|
|
|
If an exception is raised in the coroutine, the returned future will be
|
|
|
|
notified. It can also be used to cancel the task in the event loop::
|
|
|
|
|
|
|
|
try:
|
|
|
|
result = future.result(timeout)
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
print('The coroutine took too long, cancelling the task...')
|
|
|
|
future.cancel()
|
|
|
|
except Exception as exc:
|
|
|
|
print('The coroutine raised an exception: {!r}'.format(exc))
|
|
|
|
else:
|
|
|
|
print('The coroutine returned: {!r}'.format(result))
|
|
|
|
|
|
|
|
See the :ref:`concurrency and multithreading <asyncio-multithreading>`
|
|
|
|
section of the documentation.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2016-01-11 08:45:25 -04:00
|
|
|
Unlike other functions from the module,
|
|
|
|
:func:`run_coroutine_threadsafe` requires the *loop* argument to
|
2016-06-01 02:01:10 -03:00
|
|
|
be passed explicitly.
|
2016-01-11 08:40:35 -04:00
|
|
|
|
2016-01-11 09:41:43 -04:00
|
|
|
.. versionadded:: 3.5.1
|
2016-01-11 08:40:35 -04:00
|
|
|
|
2015-02-12 17:49:18 -04:00
|
|
|
.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2014-02-20 17:20:44 -04:00
|
|
|
Create a :ref:`coroutine <coroutine>` that completes after a given
|
2014-01-20 10:59:23 -04:00
|
|
|
time (in seconds). If *result* is provided, it is produced to the caller
|
|
|
|
when the coroutine completes.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2014-01-31 21:36:43 -04:00
|
|
|
The resolution of the sleep depends on the :ref:`granularity of the event
|
|
|
|
loop <asyncio-delayed-calls>`.
|
|
|
|
|
2015-02-12 17:49:18 -04:00
|
|
|
This function is a :ref:`coroutine <coroutine>`.
|
|
|
|
|
2013-12-02 20:08:00 -04:00
|
|
|
.. function:: shield(arg, \*, loop=None)
|
|
|
|
|
|
|
|
Wait for a future, shielding it from cancellation.
|
|
|
|
|
|
|
|
The statement::
|
|
|
|
|
|
|
|
res = yield from shield(something())
|
|
|
|
|
|
|
|
is exactly equivalent to the statement::
|
|
|
|
|
|
|
|
res = yield from something()
|
|
|
|
|
|
|
|
*except* that if the coroutine containing it is cancelled, the task running
|
|
|
|
in ``something()`` is not cancelled. From the point of view of
|
|
|
|
``something()``, the cancellation did not happen. But its caller is still
|
|
|
|
cancelled, so the yield-from expression still raises
|
|
|
|
:exc:`~concurrent.futures.CancelledError`. Note: If ``something()`` is
|
|
|
|
cancelled by other means this will still cancel ``shield()``.
|
|
|
|
|
|
|
|
If you want to completely ignore cancellation (not recommended) you can
|
|
|
|
combine ``shield()`` with a try/except clause, as follows::
|
|
|
|
|
|
|
|
try:
|
|
|
|
res = yield from shield(something())
|
|
|
|
except CancelledError:
|
|
|
|
res = None
|
|
|
|
|
2016-05-16 17:23:00 -03:00
|
|
|
|
2016-01-11 08:40:35 -04:00
|
|
|
.. coroutinefunction:: wait(futures, \*, loop=None, timeout=None,\
|
|
|
|
return_when=ALL_COMPLETED)
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2014-01-16 14:30:21 -04:00
|
|
|
Wait for the Futures and coroutine objects given by the sequence *futures*
|
|
|
|
to complete. Coroutines will be wrapped in Tasks. Returns two sets of
|
2013-12-03 14:17:25 -04:00
|
|
|
:class:`Future`: (done, pending).
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2014-06-10 06:16:05 -03:00
|
|
|
The sequence *futures* must not be empty.
|
|
|
|
|
2013-12-02 20:08:00 -04:00
|
|
|
*timeout* can be used to control the maximum number of seconds to wait before
|
|
|
|
returning. *timeout* can be an int or float. If *timeout* is not specified
|
|
|
|
or ``None``, there is no limit to the wait time.
|
|
|
|
|
|
|
|
*return_when* indicates when this function should return. It must be one of
|
2013-12-02 20:59:38 -04:00
|
|
|
the following constants of the :mod:`concurrent.futures` module:
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
.. tabularcolumns:: |l|L|
|
|
|
|
|
|
|
|
+-----------------------------+----------------------------------------+
|
|
|
|
| Constant | Description |
|
|
|
|
+=============================+========================================+
|
|
|
|
| :const:`FIRST_COMPLETED` | The function will return when any |
|
|
|
|
| | future finishes or is cancelled. |
|
|
|
|
+-----------------------------+----------------------------------------+
|
|
|
|
| :const:`FIRST_EXCEPTION` | The function will return when any |
|
|
|
|
| | future finishes by raising an |
|
|
|
|
| | exception. If no future raises an |
|
|
|
|
| | exception then it is equivalent to |
|
|
|
|
| | :const:`ALL_COMPLETED`. |
|
|
|
|
+-----------------------------+----------------------------------------+
|
|
|
|
| :const:`ALL_COMPLETED` | The function will return when all |
|
|
|
|
| | futures finish or are cancelled. |
|
|
|
|
+-----------------------------+----------------------------------------+
|
|
|
|
|
2014-02-20 17:20:44 -04:00
|
|
|
This function is a :ref:`coroutine <coroutine>`.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
|
|
|
Usage::
|
|
|
|
|
|
|
|
done, pending = yield from asyncio.wait(fs)
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2014-05-28 19:04:57 -03:00
|
|
|
This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done
|
|
|
|
when the timeout occurs are returned in the second set.
|
2013-12-02 20:08:00 -04:00
|
|
|
|
2013-12-02 20:22:06 -04:00
|
|
|
|
2015-02-12 17:49:18 -04:00
|
|
|
.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
|
2014-01-29 19:18:50 -04:00
|
|
|
|
|
|
|
Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>`
|
2014-07-08 07:39:10 -03:00
|
|
|
to complete with timeout. If *timeout* is ``None``, block until the future
|
2014-01-29 19:18:50 -04:00
|
|
|
completes.
|
|
|
|
|
2014-08-10 20:11:13 -03:00
|
|
|
Coroutine will be wrapped in :class:`Task`.
|
2014-01-29 19:18:50 -04:00
|
|
|
|
|
|
|
Returns result of the Future or coroutine. When a timeout occurs, it
|
2014-05-28 19:04:57 -03:00
|
|
|
cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task
|
2014-01-29 19:18:50 -04:00
|
|
|
cancellation, wrap it in :func:`shield`.
|
|
|
|
|
2015-04-03 12:08:19 -03:00
|
|
|
If the wait is cancelled, the future *fut* is also cancelled.
|
|
|
|
|
2014-07-08 07:39:10 -03:00
|
|
|
This function is a :ref:`coroutine <coroutine>`, usage::
|
2014-01-29 19:18:50 -04:00
|
|
|
|
2014-07-08 07:39:10 -03:00
|
|
|
result = yield from asyncio.wait_for(fut, 60.0)
|
2014-01-29 19:18:50 -04:00
|
|
|
|
2015-04-03 12:08:19 -03:00
|
|
|
.. versionchanged:: 3.4.3
|
|
|
|
If the wait is cancelled, the future *fut* is now also cancelled.
|