/
usr
/
share
/
doc
/
python3-docs
/
html
/
_sources
/
library
/
/usr/share/doc/python3-docs/html/_sources/library
mkdir
upload
Name
Size
Mode
Actions
2to3.rst.txt
15898
0644
edit
dl
rm
abc.rst.txt
11805
0644
edit
dl
rm
aifc.rst.txt
7503
0644
edit
dl
rm
allos.rst.txt
678
0644
edit
dl
rm
archiving.rst.txt
440
0644
edit
dl
rm
argparse.rst.txt
77480
0644
edit
dl
rm
array.rst.txt
10812
0644
edit
dl
rm
ast.rst.txt
10159
0644
edit
dl
rm
asynchat.rst.txt
8528
0644
edit
dl
rm
asyncio-dev.rst.txt
13398
0644
edit
dl
rm
asyncio-eventloop.rst.txt
33701
0644
edit
dl
rm
asyncio-eventloops.rst.txt
7660
0644
edit
dl
rm
asyncio-protocol.rst.txt
25170
0644
edit
dl
rm
asyncio-queue.rst.txt
4328
0644
edit
dl
rm
asyncio-stream.rst.txt
14363
0644
edit
dl
rm
asyncio-subprocess.rst.txt
15544
0644
edit
dl
rm
asyncio-sync.rst.txt
9078
0644
edit
dl
rm
asyncio-task.rst.txt
25406
0644
edit
dl
rm
asyncio.rst.txt
2272
0644
edit
dl
rm
asyncore.rst.txt
13624
0644
edit
dl
rm
atexit.rst.txt
3669
0644
edit
dl
rm
audioop.rst.txt
10712
0644
edit
dl
rm
base64.rst.txt
10371
0644
edit
dl
rm
bdb.rst.txt
12985
0644
edit
dl
rm
binary.rst.txt
654
0644
edit
dl
rm
binascii.rst.txt
6539
0644
edit
dl
rm
binhex.rst.txt
1709
0644
edit
dl
rm
bisect.rst.txt
5398
0644
edit
dl
rm
builtins.rst.txt
1465
0644
edit
dl
rm
bz2.rst.txt
8825
0644
edit
dl
rm
calendar.rst.txt
10988
0644
edit
dl
rm
cgi.rst.txt
22650
0644
edit
dl
rm
cgitb.rst.txt
2918
0644
edit
dl
rm
chunk.rst.txt
5094
0644
edit
dl
rm
cmath.rst.txt
9326
0644
edit
dl
rm
cmd.rst.txt
13795
0644
edit
dl
rm
code.rst.txt
7817
0644
edit
dl
rm
codecs.rst.txt
75564
0644
edit
dl
rm
codeop.rst.txt
3021
0644
edit
dl
rm
collections.abc.rst.txt
12861
0644
edit
dl
rm
collections.rst.txt
46063
0644
edit
dl
rm
colorsys.rst.txt
1820
0644
edit
dl
rm
compileall.rst.txt
8975
0644
edit
dl
rm
concurrency.rst.txt
673
0644
edit
dl
rm
concurrent.futures.rst.txt
16910
0644
edit
dl
rm
concurrent.rst.txt
171
0644
edit
dl
rm
configparser.rst.txt
48756
0644
edit
dl
rm
constants.rst.txt
3331
0644
edit
dl
rm
contextlib.rst.txt
28175
0644
edit
dl
rm
copy.rst.txt
3378
0644
edit
dl
rm
copyreg.rst.txt
2182
0644
edit
dl
rm
crypt.rst.txt
5122
0644
edit
dl
rm
crypto.rst.txt
411
0644
edit
dl
rm
csv.rst.txt
19902
0644
edit
dl
rm
ctypes.rst.txt
88613
0644
edit
dl
rm
curses.ascii.rst.txt
8920
0644
edit
dl
rm
curses.panel.rst.txt
2764
0644
edit
dl
rm
curses.rst.txt
76397
0644
edit
dl
rm
custominterp.rst.txt
569
0644
edit
dl
rm
datatypes.rst.txt
751
0644
edit
dl
rm
datetime.rst.txt
90524
0644
edit
dl
rm
dbm.rst.txt
14293
0644
edit
dl
rm
debug.rst.txt
471
0644
edit
dl
rm
decimal.rst.txt
74869
0644
edit
dl
rm
development.rst.txt
704
0644
edit
dl
rm
difflib.rst.txt
29861
0644
edit
dl
rm
dis.rst.txt
32567
0644
edit
dl
rm
distribution.rst.txt
452
0644
edit
dl
rm
distutils.rst.txt
1974
0644
edit
dl
rm
doctest.rst.txt
71743
0644
edit
dl
rm
dummy_threading.rst.txt
784
0644
edit
dl
rm
email.charset.rst.txt
9293
0644
edit
dl
rm
email.compat32-message.rst.txt
33493
0644
edit
dl
rm
email.contentmanager.rst.txt
9112
0644
edit
dl
rm
email.encoders.rst.txt
2715
0644
edit
dl
rm
email.errors.rst.txt
4792
0644
edit
dl
rm
email.examples.rst.txt
1915
0644
edit
dl
rm
email.generator.rst.txt
13637
0644
edit
dl
rm
email.header.rst.txt
9188
0644
edit
dl
rm
email.headerregistry.rst.txt
17957
0644
edit
dl
rm
email.iterators.rst.txt
2795
0644
edit
dl
rm
email.message.rst.txt
33008
0644
edit
dl
rm
email.mime.rst.txt
11721
0644
edit
dl
rm
email.parser.rst.txt
14092
0644
edit
dl
rm
email.policy.rst.txt
27022
0644
edit
dl
rm
email.rst.txt
6785
0644
edit
dl
rm
email.util.rst.txt
9214
0644
edit
dl
rm
ensurepip.rst.txt
4987
0644
edit
dl
rm
enum.rst.txt
32751
0644
edit
dl
rm
errno.rst.txt
6811
0644
edit
dl
rm
exceptions.rst.txt
25570
0644
edit
dl
rm
faulthandler.rst.txt
6136
0644
edit
dl
rm
fcntl.rst.txt
7152
0644
edit
dl
rm
filecmp.rst.txt
5623
0644
edit
dl
rm
fileformats.rst.txt
287
0644
edit
dl
rm
fileinput.rst.txt
8051
0644
edit
dl
rm
filesys.rst.txt
961
0644
edit
dl
rm
fnmatch.rst.txt
3103
0644
edit
dl
rm
formatter.rst.txt
13242
0644
edit
dl
rm
fpectl.rst.txt
4180
0644
edit
dl
rm
fractions.rst.txt
6364
0644
edit
dl
rm
frameworks.rst.txt
391
0644
edit
dl
rm
ftplib.rst.txt
17552
0644
edit
dl
rm
functional.rst.txt
365
0644
edit
dl
rm
functions.rst.txt
71621
0644
edit
dl
rm
functools.rst.txt
18503
0644
edit
dl
rm
gc.rst.txt
9694
0644
edit
dl
rm
getopt.rst.txt
6557
0644
edit
dl
rm
getpass.rst.txt
1882
0644
edit
dl
rm
gettext.rst.txt
25588
0644
edit
dl
rm
glob.rst.txt
3508
0644
edit
dl
rm
grp.rst.txt
2417
0644
edit
dl
rm
gzip.rst.txt
8301
0644
edit
dl
rm
hashlib.rst.txt
26523
0644
edit
dl
rm
heapq.rst.txt
13402
0644
edit
dl
rm
hmac.rst.txt
4020
0644
edit
dl
rm
html.entities.rst.txt
1319
0644
edit
dl
rm
html.parser.rst.txt
11275
0644
edit
dl
rm
html.rst.txt
1304
0644
edit
dl
rm
http.client.rst.txt
18870
0644
edit
dl
rm
http.cookiejar.rst.txt
27832
0644
edit
dl
rm
http.cookies.rst.txt
8645
0644
edit
dl
rm
http.rst.txt
7096
0644
edit
dl
rm
http.server.rst.txt
17639
0644
edit
dl
rm
i18n.rst.txt
408
0644
edit
dl
rm
idle.rst.txt
25834
0644
edit
dl
rm
imaplib.rst.txt
20367
0644
edit
dl
rm
imghdr.rst.txt
2938
0644
edit
dl
rm
imp.rst.txt
15548
0644
edit
dl
rm
importlib.rst.txt
53563
0644
edit
dl
rm
index.rst.txt
2258
0644
edit
dl
rm
inspect.rst.txt
53928
0644
edit
dl
rm
internet.rst.txt
992
0644
edit
dl
rm
intro.rst.txt
2645
0644
edit
dl
rm
io.rst.txt
40328
0644
edit
dl
rm
ipaddress.rst.txt
32340
0644
edit
dl
rm
ipc.rst.txt
649
0644
edit
dl
rm
itertools.rst.txt
38459
0644
edit
dl
rm
json.rst.txt
27876
0644
edit
dl
rm
keyword.rst.txt
617
0644
edit
dl
rm
language.rst.txt
522
0644
edit
dl
rm
linecache.rst.txt
2408
0644
edit
dl
rm
locale.rst.txt
25470
0644
edit
dl
rm
logging.config.rst.txt
33886
0644
edit
dl
rm
logging.handlers.rst.txt
42497
0644
edit
dl
rm
logging.rst.txt
60479
0644
edit
dl
rm
lzma.rst.txt
17361
0644
edit
dl
rm
macpath.rst.txt
707
0644
edit
dl
rm
mailbox.rst.txt
63055
0644
edit
dl
rm
mailcap.rst.txt
3691
0644
edit
dl
rm
markup.rst.txt
679
0644
edit
dl
rm
marshal.rst.txt
4855
0644
edit
dl
rm
math.rst.txt
14375
0644
edit
dl
rm
mimetypes.rst.txt
9839
0644
edit
dl
rm
misc.rst.txt
247
0644
edit
dl
rm
mm.rst.txt
431
0644
edit
dl
rm
mmap.rst.txt
11232
0644
edit
dl
rm
modulefinder.rst.txt
3240
0644
edit
dl
rm
modules.rst.txt
355
0644
edit
dl
rm
msilib.rst.txt
18612
0644
edit
dl
rm
msvcrt.rst.txt
4392
0644
edit
dl
rm
multiprocessing.rst.txt
104494
0644
edit
dl
rm
netdata.rst.txt
339
0644
edit
dl
rm
netrc.rst.txt
3007
0644
edit
dl
rm
nis.rst.txt
1993
0644
edit
dl
rm
nntplib.rst.txt
21821
0644
edit
dl
rm
numbers.rst.txt
8089
0644
edit
dl
rm
numeric.rst.txt
696
0644
edit
dl
rm
operator.rst.txt
18989
0644
edit
dl
rm
optparse.rst.txt
76996
0644
edit
dl
rm
os.path.rst.txt
16419
0644
edit
dl
rm
os.rst.txt
137534
0644
edit
dl
rm
ossaudiodev.rst.txt
17845
0644
edit
dl
rm
othergui.rst.txt
2822
0644
edit
dl
rm
parser.rst.txt
15148
0644
edit
dl
rm
pathlib.rst.txt
30045
0644
edit
dl
rm
pdb.rst.txt
19454
0644
edit
dl
rm
persistence.rst.txt
591
0644
edit
dl
rm
pickle.rst.txt
37440
0644
edit
dl
rm
pickletools.rst.txt
3729
0644
edit
dl
rm
pipes.rst.txt
2557
0644
edit
dl
rm
pkgutil.rst.txt
8730
0644
edit
dl
rm
platform.rst.txt
9624
0644
edit
dl
rm
plistlib.rst.txt
7398
0644
edit
dl
rm
poplib.rst.txt
8197
0644
edit
dl
rm
posix.rst.txt
3694
0644
edit
dl
rm
pprint.rst.txt
14274
0644
edit
dl
rm
profile.rst.txt
27969
0644
edit
dl
rm
pty.rst.txt
3123
0644
edit
dl
rm
pwd.rst.txt
2739
0644
edit
dl
rm
pyclbr.rst.txt
3297
0644
edit
dl
rm
pydoc.rst.txt
4688
0644
edit
dl
rm
pyexpat.rst.txt
28620
0644
edit
dl
rm
python.rst.txt
475
0644
edit
dl
rm
py_compile.rst.txt
3851
0644
edit
dl
rm
queue.rst.txt
7268
0644
edit
dl
rm
quopri.rst.txt
2571
0644
edit
dl
rm
random.rst.txt
18503
0644
edit
dl
rm
re.rst.txt
64936
0644
edit
dl
rm
readline.rst.txt
11943
0644
edit
dl
rm
reprlib.rst.txt
5162
0644
edit
dl
rm
resource.rst.txt
12291
0644
edit
dl
rm
rlcompleter.rst.txt
2294
0644
edit
dl
rm
runpy.rst.txt
8285
0644
edit
dl
rm
sched.rst.txt
4842
0644
edit
dl
rm
secrets.rst.txt
5930
0644
edit
dl
rm
select.rst.txt
28175
0644
edit
dl
rm
selectors.rst.txt
8925
0644
edit
dl
rm
shelve.rst.txt
8390
0644
edit
dl
rm
shlex.rst.txt
16441
0644
edit
dl
rm
shutil.rst.txt
26014
0644
edit
dl
rm
signal.rst.txt
17218
0644
edit
dl
rm
site.rst.txt
9628
0644
edit
dl
rm
smtpd.rst.txt
10806
0644
edit
dl
rm
smtplib.rst.txt
23439
0644
edit
dl
rm
sndhdr.rst.txt
1994
0644
edit
dl
rm
socket.rst.txt
68202
0644
edit
dl
rm
socketserver.rst.txt
23712
0644
edit
dl
rm
spwd.rst.txt
2958
0644
edit
dl
rm
sqlite3.rst.txt
39215
0644
edit
dl
rm
ssl.rst.txt
96021
0644
edit
dl
rm
stat.rst.txt
9805
0644
edit
dl
rm
statistics.rst.txt
15301
0644
edit
dl
rm
stdtypes.rst.txt
179240
0644
edit
dl
rm
string.rst.txt
35374
0644
edit
dl
rm
stringprep.rst.txt
4279
0644
edit
dl
rm
struct.rst.txt
19581
0644
edit
dl
rm
subprocess.rst.txt
45793
0644
edit
dl
rm
sunau.rst.txt
7390
0644
edit
dl
rm
superseded.rst.txt
258
0644
edit
dl
rm
symbol.rst.txt
975
0644
edit
dl
rm
symtable.rst.txt
4964
0644
edit
dl
rm
sys.rst.txt
58273
0644
edit
dl
rm
sysconfig.rst.txt
8749
0644
edit
dl
rm
syslog.rst.txt
4302
0644
edit
dl
rm
tabnanny.rst.txt
2007
0644
edit
dl
rm
tarfile.rst.txt
31749
0644
edit
dl
rm
telnetlib.rst.txt
7899
0644
edit
dl
rm
tempfile.rst.txt
13857
0644
edit
dl
rm
termios.rst.txt
3751
0644
edit
dl
rm
test.rst.txt
25764
0644
edit
dl
rm
text.rst.txt
584
0644
edit
dl
rm
textwrap.rst.txt
10519
0644
edit
dl
rm
threading.rst.txt
39257
0644
edit
dl
rm
time.rst.txt
32967
0644
edit
dl
rm
timeit.rst.txt
13000
0644
edit
dl
rm
tk.rst.txt
1639
0644
edit
dl
rm
tkinter.rst.txt
33027
0644
edit
dl
rm
tkinter.scrolledtext.rst.txt
1255
0644
edit
dl
rm
tkinter.tix.rst.txt
22653
0644
edit
dl
rm
tkinter.ttk.rst.txt
58489
0644
edit
dl
rm
token.rst.txt
2607
0644
edit
dl
rm
tokenize.rst.txt
10002
0644
edit
dl
rm
trace.rst.txt
6914
0644
edit
dl
rm
traceback.rst.txt
17854
0644
edit
dl
rm
tracemalloc.rst.txt
22089
0644
edit
dl
rm
tty.rst.txt
1097
0644
edit
dl
rm
turtle.rst.txt
71221
0644
edit
dl
rm
types.rst.txt
9999
0644
edit
dl
rm
typing.rst.txt
34332
0644
edit
dl
rm
undoc.rst.txt
780
0644
edit
dl
rm
unicodedata.rst.txt
5762
0644
edit
dl
rm
unittest.mock-examples.rst.txt
46206
0644
edit
dl
rm
unittest.mock.rst.txt
85991
0644
edit
dl
rm
unittest.rst.txt
93304
0644
edit
dl
rm
unix.rst.txt
446
0644
edit
dl
rm
urllib.error.rst.txt
2199
0644
edit
dl
rm
urllib.parse.rst.txt
27332
0644
edit
dl
rm
urllib.request.rst.txt
59360
0644
edit
dl
rm
urllib.robotparser.rst.txt
2969
0644
edit
dl
rm
urllib.rst.txt
466
0644
edit
dl
rm
uu.rst.txt
2387
0644
edit
dl
rm
uuid.rst.txt
8760
0644
edit
dl
rm
venv.rst.txt
20621
0644
edit
dl
rm
warnings.rst.txt
20152
0644
edit
dl
rm
wave.rst.txt
6870
0644
edit
dl
rm
weakref.rst.txt
21328
0644
edit
dl
rm
webbrowser.rst.txt
9783
0644
edit
dl
rm
windows.rst.txt
272
0644
edit
dl
rm
winreg.rst.txt
24073
0644
edit
dl
rm
winsound.rst.txt
5134
0644
edit
dl
rm
wsgiref.rst.txt
33047
0644
edit
dl
rm
xdrlib.rst.txt
8078
0644
edit
dl
rm
xml.dom.minidom.rst.txt
10198
0644
edit
dl
rm
xml.dom.pulldom.rst.txt
5186
0644
edit
dl
rm
xml.dom.rst.txt
39507
0644
edit
dl
rm
xml.etree.elementtree.rst.txt
43871
0644
edit
dl
rm
xml.rst.txt
6071
0644
edit
dl
rm
xml.sax.handler.rst.txt
15399
0644
edit
dl
rm
xml.sax.reader.rst.txt
12133
0644
edit
dl
rm
xml.sax.rst.txt
7159
0644
edit
dl
rm
xml.sax.utils.rst.txt
3901
0644
edit
dl
rm
xmlrpc.client.rst.txt
23071
0644
edit
dl
rm
xmlrpc.rst.txt
475
0644
edit
dl
rm
xmlrpc.server.rst.txt
14990
0644
edit
dl
rm
zipapp.rst.txt
17392
0644
edit
dl
rm
zipfile.rst.txt
24005
0644
edit
dl
rm
zipimport.rst.txt
5805
0644
edit
dl
rm
zlib.rst.txt
13912
0644
edit
dl
rm
_dummy_thread.rst.txt
762
0644
edit
dl
rm
_thread.rst.txt
6886
0644
edit
dl
rm
__future__.rst.txt
5245
0644
edit
dl
rm
__main__.rst.txt
904
0644
edit
dl
rm
Edit:
/usr/share/doc/python3-docs/html/_sources/library/asyncio-task.rst.txt
(25406B)
.. currentmodule:: asyncio Tasks and coroutines ==================== **Source code:** :source:`Lib/asyncio/tasks.py` **Source code:** :source:`Lib/asyncio/coroutines.py` .. _coroutine: Coroutines ---------- 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`, instead of the original ``yield`` syntax. The word "coroutine", like the word "generator", is used for two different (though related) concepts: - The function that defines a coroutine (a function definition using :keyword:`async def` or decorated with ``@asyncio.coroutine``). If disambiguation is needed we will call this a *coroutine function* (:func:`iscoroutinefunction` returns ``True``). - 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 call it a *coroutine object* (:func:`iscoroutine` returns ``True``). Things a coroutine can do: - ``result = await future`` or ``result = yield from future`` -- suspends the coroutine until the 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. - ``result = await coroutine`` or ``result = yield from coroutine`` -- wait for another coroutine to 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 waiting for this one using :keyword:`await` or ``yield from``. - ``raise exception`` -- raise an exception in the coroutine that is waiting for this one using :keyword:`await` or ``yield from``. 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 (assuming the other coroutine is already running!), or schedule its execution using the :func:`ensure_future` function or the :meth:`AbstractEventLoop.create_task` method. Coroutines (and tasks) can only run when the event loop is running. .. decorator:: coroutine 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. If the generator is not yielded from before it is destroyed, an error message is logged. See :ref:`Detect coroutines never scheduled <asyncio-coroutine-not-scheduled>`. .. 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 used in a callback-style code, wrap its result with :func:`ensure_future`. .. _asyncio-hello-world-coroutine: Example: Hello World coroutine ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Example of coroutine displaying ``"Hello World"``:: import asyncio async def hello_world(): 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>` example uses the :meth:`AbstractEventLoop.call_soon` method to schedule a 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 async def display_date(loop): end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break await asyncio.sleep(1) loop = asyncio.get_event_loop() # Blocking call which returns when the display_date() coroutine is done loop.run_until_complete(display_date(loop)) loop.close() .. seealso:: The :ref:`display the current date with call_later() <asyncio-date-callback>` example uses a callback with the :meth:`AbstractEventLoop.call_later` method. Example: Chain coroutines ^^^^^^^^^^^^^^^^^^^^^^^^^ Example chaining coroutines:: import asyncio async def compute(x, y): print("Compute %s + %s ..." % (x, y)) await asyncio.sleep(1.0) return x + y async def print_sum(x, y): result = await compute(x, y) print("%s + %s = %s" % (x, y, result)) loop = asyncio.get_event_loop() loop.run_until_complete(print_sum(1, 2)) loop.close() ``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits until ``compute()`` is completed before returning its result. Sequence diagram of the example: .. image:: tulip_coro.png :align: center The "Task" is created by the :meth:`AbstractEventLoop.run_until_complete` method when it gets a coroutine object instead of a task. The diagram shows the control flow, it does not describe exactly how things work internally. For example, the sleep coroutine creates an internal future which uses :meth:`AbstractEventLoop.call_later` to wake up the task in 1 second. InvalidStateError ----------------- .. exception:: InvalidStateError The operation is not allowed in this state. TimeoutError ------------ .. exception:: TimeoutError The operation exceeded the given deadline. .. note:: This exception is different from the builtin :exc:`TimeoutError` exception! 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 via the event loop's :meth:`~AbstractEventLoop.call_soon`. - This class is not compatible with the :func:`~concurrent.futures.wait` and :func:`~concurrent.futures.as_completed` functions in the :mod:`concurrent.futures` package. This class is :ref:`not thread safe <asyncio-multithreading>`. .. 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 with :meth:`~AbstractEventLoop.call_soon`. :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)``. .. 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`. Example: Future with run_until_complete() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Example combining a :class:`Future` and a :ref:`coroutine function <coroutine>`:: import asyncio async def slow_operation(future): await asyncio.sleep(1) future.set_result('Future is done!') loop = asyncio.get_event_loop() future = asyncio.Future() asyncio.ensure_future(slow_operation(future)) loop.run_until_complete(future) print(future.result()) loop.close() The coroutine function is responsible for the computation (which takes 1 second) and it stores the result into the future. The :meth:`~AbstractEventLoop.run_until_complete` method waits for the completion of the future. .. note:: The :meth:`~AbstractEventLoop.run_until_complete` method uses internally the :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 async def slow_operation(future): await asyncio.sleep(1) future.set_result('Future is done!') def got_result(future): print(future.result()) loop.stop() loop = asyncio.get_event_loop() future = asyncio.Future() asyncio.ensure_future(slow_operation(future)) future.add_done_callback(got_result) try: loop.run_forever() finally: loop.close() 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. Task ---- .. class:: Task(coro, \*, loop=None) Schedule the execution of a :ref:`coroutine <coroutine>`: wrap it in a future. A task is a subclass of :class:`Future`. A task is responsible for executing a coroutine object in an event loop. If the wrapped coroutine yields from a future, the task suspends the execution of the wrapped coroutine and waits for the completion of the future. When 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 a time. Other tasks may run in parallel if other event loops are running in different threads. While a task waits for the completion of a future, the event loop executes a new task. 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 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>`. Don't directly create :class:`Task` instances: use the :func:`ensure_future` function or the :meth:`AbstractEventLoop.create_task` method. This class is :ref:`not thread safe <asyncio-multithreading>`. .. 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. .. 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`. .. method:: cancel() Request that this task cancel itself. 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. Unlike :meth:`Future.cancel`, this does not guarantee that the task will be cancelled: the exception might be caught and acted upon, delaying cancellation of the task or preventing cancellation completely. The task may also return a value or raise a different exception. 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) Return the list of stack frames for this task's coroutine. 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. The frames are always ordered from oldest to newest. The optional limit gives the maximum number of frames to return; by 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 is written; by default output is written to sys.stderr. Example: Parallel execution of tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Example executing 3 tasks (A, B, C) in parallel:: import asyncio async def factorial(name, number): f = 1 for i in range(2, number+1): print("Task %s: Compute factorial(%s)..." % (name, i)) await asyncio.sleep(1) f *= i print("Task %s: factorial(%s) = %s" % (name, number, f)) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather( factorial("A", 2), factorial("B", 3), factorial("C", 4), )) loop.close() Output:: 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 loop stops when all tasks are done. Task functions -------------- .. note:: In the functions below, the optional *loop* argument allows explicitly setting the event loop object used by the underlying task or coroutine. If it's not provided, the default event loop is used. .. function:: as_completed(fs, \*, loop=None, timeout=None) Return an iterator whose values, when waited for, are :class:`Future` instances. Raises :exc:`asyncio.TimeoutError` if the timeout occurs before all Futures are done. 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. .. function:: ensure_future(coro_or_future, \*, loop=None) Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in a future. Return a :class:`Task` object. If the argument is a :class:`Future`, it is returned directly. .. versionadded:: 3.4.4 .. versionchanged:: 3.5.1 The function accepts any :term:`awaitable` object. .. seealso:: The :meth:`AbstractEventLoop.create_task` method. .. function:: async(coro_or_future, \*, loop=None) A deprecated alias to :func:`ensure_future`. .. deprecated:: 3.4.4 .. function:: wrap_future(future, \*, loop=None) Wrap a :class:`concurrent.futures.Future` object in a :class:`Future` object. .. function:: gather(\*coros_or_futures, loop=None, return_exceptions=False) Return a future aggregating results from the given coroutine objects or futures. 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 arrival). If *return_exceptions* is true, exceptions in the tasks are 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.) .. versionchanged:: 3.6.6 If the *gather* itself is cancelled, the cancellation is propagated regardless of *return_exceptions*. .. function:: iscoroutine(obj) Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`, which may be based on a generator or an :keyword:`async def` coroutine. .. function:: iscoroutinefunction(func) 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. .. 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:: Unlike other functions from the module, :func:`run_coroutine_threadsafe` requires the *loop* argument to be passed explicitly. .. versionadded:: 3.5.1 .. coroutinefunction:: sleep(delay, result=None, \*, loop=None) Create a :ref:`coroutine <coroutine>` that completes after a given time (in seconds). If *result* is provided, it is produced to the caller when the coroutine completes. The resolution of the sleep depends on the :ref:`granularity of the event loop <asyncio-delayed-calls>`. This function is a :ref:`coroutine <coroutine>`. .. coroutinefunction:: 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 .. coroutinefunction:: wait(futures, \*, loop=None, timeout=None,\ return_when=ALL_COMPLETED) Wait for the Futures and coroutine objects given by the sequence *futures* to complete. Coroutines will be wrapped in Tasks. Returns two sets of :class:`Future`: (done, pending). The sequence *futures* must not be empty. *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 the following constants of the :mod:`concurrent.futures` module: .. 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. | +-----------------------------+----------------------------------------+ This function is a :ref:`coroutine <coroutine>`. Usage:: done, pending = yield from asyncio.wait(fs) .. note:: This does not raise :exc:`asyncio.TimeoutError`! Futures that aren't done when the timeout occurs are returned in the second set. .. coroutinefunction:: wait_for(fut, timeout, \*, loop=None) Wait for the single :class:`Future` or :ref:`coroutine object <coroutine>` to complete with timeout. If *timeout* is ``None``, block until the future completes. Coroutine will be wrapped in :class:`Task`. Returns result of the Future or coroutine. When a timeout occurs, it cancels the task and raises :exc:`asyncio.TimeoutError`. To avoid the task cancellation, wrap it in :func:`shield`. If the wait is cancelled, the future *fut* is also cancelled. This function is a :ref:`coroutine <coroutine>`, usage:: result = yield from asyncio.wait_for(fut, 60.0) .. versionchanged:: 3.4.3 If the wait is cancelled, the future *fut* is now also cancelled.
Save
cmd:
run