/
usr
/
share
/
doc
/
python3-docs
/
html
/
library
/
/usr/share/doc/python3-docs/html/library
mkdir
upload
Name
Size
Mode
Actions
2to3.html
61709
0644
edit
dl
rm
abc.html
41394
0644
edit
dl
rm
aifc.html
28114
0644
edit
dl
rm
allos.html
32236
0644
edit
dl
rm
archiving.html
11992
0644
edit
dl
rm
argparse.html
274984
0644
edit
dl
rm
array.html
33547
0644
edit
dl
rm
ast.html
39595
0644
edit
dl
rm
asynchat.html
32546
0644
edit
dl
rm
asyncio-dev.html
51869
0644
edit
dl
rm
asyncio-eventloop.html
111215
0644
edit
dl
rm
asyncio-eventloops.html
33026
0644
edit
dl
rm
asyncio-protocol.html
87431
0644
edit
dl
rm
asyncio-queue.html
23957
0644
edit
dl
rm
asyncio-stream.html
61005
0644
edit
dl
rm
asyncio-subprocess.html
58015
0644
edit
dl
rm
asyncio-sync.html
35678
0644
edit
dl
rm
asyncio-task.html
83968
0644
edit
dl
rm
asyncio.html
28026
0644
edit
dl
rm
asyncore.html
42706
0644
edit
dl
rm
atexit.html
18433
0644
edit
dl
rm
audioop.html
35442
0644
edit
dl
rm
base64.html
36454
0644
edit
dl
rm
bdb.html
43423
0644
edit
dl
rm
binary.html
12723
0644
edit
dl
rm
binascii.html
24745
0644
edit
dl
rm
binhex.html
11669
0644
edit
dl
rm
bisect.html
25602
0644
edit
dl
rm
builtins.html
11604
0644
edit
dl
rm
bz2.html
33358
0644
edit
dl
rm
calendar.html
39539
0644
edit
dl
rm
cgi.html
55881
0644
edit
dl
rm
cgitb.html
12765
0644
edit
dl
rm
chunk.html
16872
0644
edit
dl
rm
cmath.html
34171
0644
edit
dl
rm
cmd.html
43811
0644
edit
dl
rm
code.html
27886
0644
edit
dl
rm
codecs.html
134071
0644
edit
dl
rm
codeop.html
14304
0644
edit
dl
rm
collections.abc.html
60912
0644
edit
dl
rm
collections.html
154946
0644
edit
dl
rm
colorsys.html
12627
0644
edit
dl
rm
compileall.html
28263
0644
edit
dl
rm
concurrency.html
21203
0644
edit
dl
rm
concurrent.futures.html
60660
0644
edit
dl
rm
concurrent.html
7959
0644
edit
dl
rm
configparser.html
141052
0644
edit
dl
rm
constants.html
17500
0644
edit
dl
rm
contextlib.html
88801
0644
edit
dl
rm
copy.html
13841
0644
edit
dl
rm
copyreg.html
14725
0644
edit
dl
rm
crypt.html
20331
0644
edit
dl
rm
crypto.html
10914
0644
edit
dl
rm
csv.html
69043
0644
edit
dl
rm
ctypes.html
264529
0644
edit
dl
rm
curses.ascii.html
25197
0644
edit
dl
rm
curses.html
175551
0644
edit
dl
rm
curses.panel.html
16706
0644
edit
dl
rm
custominterp.html
8734
0644
edit
dl
rm
datatypes.html
23950
0644
edit
dl
rm
datetime.html
306435
0644
edit
dl
rm
dbm.html
43119
0644
edit
dl
rm
debug.html
13983
0644
edit
dl
rm
decimal.html
233486
0644
edit
dl
rm
development.html
25123
0644
edit
dl
rm
difflib.html
96156
0644
edit
dl
rm
dis.html
106191
0644
edit
dl
rm
distribution.html
10506
0644
edit
dl
rm
distutils.html
10884
0644
edit
dl
rm
doctest.html
179752
0644
edit
dl
rm
dummy_threading.html
9316
0644
edit
dl
rm
email.charset.html
26431
0644
edit
dl
rm
email.compat32-message.html
86150
0644
edit
dl
rm
email.contentmanager.html
30028
0644
edit
dl
rm
email.encoders.html
14250
0644
edit
dl
rm
email.errors.html
19704
0644
edit
dl
rm
email.examples.html
57872
0644
edit
dl
rm
email.generator.html
41798
0644
edit
dl
rm
email.header.html
31219
0644
edit
dl
rm
email.headerregistry.html
57670
0644
edit
dl
rm
email.html
27741
0644
edit
dl
rm
email.iterators.html
13532
0644
edit
dl
rm
email.message.html
87210
0644
edit
dl
rm
email.mime.html
36081
0644
edit
dl
rm
email.parser.html
47430
0644
edit
dl
rm
email.policy.html
75241
0644
edit
dl
rm
email.util.html
33853
0644
edit
dl
rm
ensurepip.html
18700
0644
edit
dl
rm
enum.html
133949
0644
edit
dl
rm
errno.html
41331
0644
edit
dl
rm
exceptions.html
85151
0644
edit
dl
rm
faulthandler.html
23396
0644
edit
dl
rm
fcntl.html
27321
0644
edit
dl
rm
filecmp.html
25036
0644
edit
dl
rm
fileformats.html
11129
0644
edit
dl
rm
fileinput.html
30030
0644
edit
dl
rm
filesys.html
13418
0644
edit
dl
rm
fnmatch.html
16987
0644
edit
dl
rm
formatter.html
37666
0644
edit
dl
rm
fpectl.html
17538
0644
edit
dl
rm
fractions.html
29918
0644
edit
dl
rm
frameworks.html
13471
0644
edit
dl
rm
ftplib.html
54429
0644
edit
dl
rm
functional.html
9002
0644
edit
dl
rm
functions.html
201486
0644
edit
dl
rm
functools.html
64951
0644
edit
dl
rm
gc.html
29524
0644
edit
dl
rm
getopt.html
25353
0644
edit
dl
rm
getpass.html
12061
0644
edit
dl
rm
gettext.html
76641
0644
edit
dl
rm
glob.html
18432
0644
edit
dl
rm
grp.html
12383
0644
edit
dl
rm
gzip.html
32669
0644
edit
dl
rm
hashlib.html
79554
0644
edit
dl
rm
heapq.html
35529
0644
edit
dl
rm
hmac.html
17827
0644
edit
dl
rm
html.entities.html
11361
0644
edit
dl
rm
html.html
11108
0644
edit
dl
rm
html.parser.html
41842
0644
edit
dl
rm
http.client.html
65250
0644
edit
dl
rm
http.cookiejar.html
96195
0644
edit
dl
rm
http.cookies.html
39329
0644
edit
dl
rm
http.html
37602
0644
edit
dl
rm
http.server.html
58191
0644
edit
dl
rm
i18n.html
10464
0644
edit
dl
rm
idle.html
48412
0644
edit
dl
rm
imaplib.html
67339
0644
edit
dl
rm
imghdr.html
13456
0644
edit
dl
rm
imp.html
48153
0644
edit
dl
rm
importlib.html
173109
0644
edit
dl
rm
index.html
67768
0644
edit
dl
rm
inspect.html
130355
0644
edit
dl
rm
internet.html
31087
0644
edit
dl
rm
intro.html
9904
0644
edit
dl
rm
io.html
122685
0644
edit
dl
rm
ipaddress.html
105873
0644
edit
dl
rm
ipc.html
33743
0644
edit
dl
rm
itertools.html
132824
0644
edit
dl
rm
json.html
81078
0644
edit
dl
rm
keyword.html
8918
0644
edit
dl
rm
language.html
13648
0644
edit
dl
rm
linecache.html
13492
0644
edit
dl
rm
locale.html
61540
0644
edit
dl
rm
logging.config.html
85489
0644
edit
dl
rm
logging.handlers.html
112397
0644
edit
dl
rm
logging.html
134850
0644
edit
dl
rm
lzma.html
56484
0644
edit
dl
rm
macpath.html
9257
0644
edit
dl
rm
mailbox.html
157315
0644
edit
dl
rm
mailcap.html
14676
0644
edit
dl
rm
markup.html
19356
0644
edit
dl
rm
marshal.html
18317
0644
edit
dl
rm
math.html
53661
0644
edit
dl
rm
mimetypes.html
31410
0644
edit
dl
rm
misc.html
8123
0644
edit
dl
rm
mm.html
10022
0644
edit
dl
rm
mmap.html
34294
0644
edit
dl
rm
modulefinder.html
18559
0644
edit
dl
rm
modules.html
10914
0644
edit
dl
rm
msilib.html
57205
0644
edit
dl
rm
msvcrt.html
21989
0644
edit
dl
rm
multiprocessing.html
365487
0644
edit
dl
rm
netdata.html
17470
0644
edit
dl
rm
netrc.html
14568
0644
edit
dl
rm
nis.html
11659
0644
edit
dl
rm
nntplib.html
69601
0644
edit
dl
rm
numbers.html
41432
0644
edit
dl
rm
numeric.html
15535
0644
edit
dl
rm
operator.html
81460
0644
edit
dl
rm
optparse.html
249942
0644
edit
dl
rm
os.html
398039
0644
edit
dl
rm
os.path.html
53818
0644
edit
dl
rm
ossaudiodev.html
47947
0644
edit
dl
rm
othergui.html
10256
0644
edit
dl
rm
parser.html
42408
0644
edit
dl
rm
pathlib.html
116726
0644
edit
dl
rm
pdb.html
52661
0644
edit
dl
rm
persistence.html
15281
0644
edit
dl
rm
pickle.html
115052
0644
edit
dl
rm
pickletools.html
17094
0644
edit
dl
rm
pipes.html
15991
0644
edit
dl
rm
pkgutil.html
31878
0644
edit
dl
rm
platform.html
33728
0644
edit
dl
rm
plistlib.html
29290
0644
edit
dl
rm
poplib.html
30940
0644
edit
dl
rm
posix.html
17608
0644
edit
dl
rm
pprint.html
41969
0644
edit
dl
rm
profile.html
71848
0644
edit
dl
rm
pty.html
17594
0644
edit
dl
rm
pwd.html
13098
0644
edit
dl
rm
pyclbr.html
16520
0644
edit
dl
rm
pydoc.html
15991
0644
edit
dl
rm
pyexpat.html
88938
0644
edit
dl
rm
python.html
17133
0644
edit
dl
rm
py_compile.html
15508
0644
edit
dl
rm
queue.html
28199
0644
edit
dl
rm
quopri.html
13858
0644
edit
dl
rm
random.html
60646
0644
edit
dl
rm
re.html
191176
0644
edit
dl
rm
readline.html
42133
0644
edit
dl
rm
reprlib.html
24964
0644
edit
dl
rm
resource.html
36552
0644
edit
dl
rm
rlcompleter.html
14392
0644
edit
dl
rm
runpy.html
26607
0644
edit
dl
rm
sched.html
20034
0644
edit
dl
rm
secrets.html
24734
0644
edit
dl
rm
select.html
62819
0644
edit
dl
rm
selectors.html
35845
0644
edit
dl
rm
shelve.html
28777
0644
edit
dl
rm
shlex.html
48979
0644
edit
dl
rm
shutil.html
74207
0644
edit
dl
rm
signal.html
55064
0644
edit
dl
rm
site.html
32242
0644
edit
dl
rm
smtpd.html
35892
0644
edit
dl
rm
smtplib.html
68433
0644
edit
dl
rm
sndhdr.html
12439
0644
edit
dl
rm
socket.html
196077
0644
edit
dl
rm
socketserver.html
81918
0644
edit
dl
rm
spwd.html
12328
0644
edit
dl
rm
sqlite3.html
161872
0644
edit
dl
rm
ssl.html
266327
0644
edit
dl
rm
stat.html
44722
0644
edit
dl
rm
statistics.html
50050
0644
edit
dl
rm
stdtypes.html
465658
0644
edit
dl
rm
string.html
95262
0644
edit
dl
rm
stringprep.html
18654
0644
edit
dl
rm
struct.html
51100
0644
edit
dl
rm
subprocess.html
141926
0644
edit
dl
rm
sunau.html
31757
0644
edit
dl
rm
superseded.html
13781
0644
edit
dl
rm
symbol.html
8848
0644
edit
dl
rm
symtable.html
26112
0644
edit
dl
rm
sys.html
141670
0644
edit
dl
rm
sysconfig.html
30259
0644
edit
dl
rm
syslog.html
21026
0644
edit
dl
rm
tabnanny.html
12269
0644
edit
dl
rm
tarfile.html
96758
0644
edit
dl
rm
telnetlib.html
30409
0644
edit
dl
rm
tempfile.html
41394
0644
edit
dl
rm
termios.html
18181
0644
edit
dl
rm
test.html
78555
0644
edit
dl
rm
text.html
13786
0644
edit
dl
rm
textwrap.html
37998
0644
edit
dl
rm
threading.html
103464
0644
edit
dl
rm
time.html
79629
0644
edit
dl
rm
timeit.html
45249
0644
edit
dl
rm
tk.html
23299
0644
edit
dl
rm
tkinter.html
82932
0644
edit
dl
rm
tkinter.scrolledtext.html
9957
0644
edit
dl
rm
tkinter.tix.html
51858
0644
edit
dl
rm
tkinter.ttk.html
110673
0644
edit
dl
rm
token.html
22660
0644
edit
dl
rm
tokenize.html
32149
0644
edit
dl
rm
trace.html
29145
0644
edit
dl
rm
traceback.html
57588
0644
edit
dl
rm
tracemalloc.html
101144
0644
edit
dl
rm
tty.html
10540
0644
edit
dl
rm
turtle.html
250367
0644
edit
dl
rm
types.html
37060
0644
edit
dl
rm
typing.html
139175
0644
edit
dl
rm
undoc.html
9181
0644
edit
dl
rm
unicodedata.html
21108
0644
edit
dl
rm
unittest.html
250689
0644
edit
dl
rm
unittest.mock-examples.html
168144
0644
edit
dl
rm
unittest.mock.html
300089
0644
edit
dl
rm
unix.html
11780
0644
edit
dl
rm
urllib.error.html
14474
0644
edit
dl
rm
urllib.html
9566
0644
edit
dl
rm
urllib.parse.html
76334
0644
edit
dl
rm
urllib.request.html
177199
0644
edit
dl
rm
urllib.robotparser.html
17156
0644
edit
dl
rm
uu.html
12209
0644
edit
dl
rm
uuid.html
31957
0644
edit
dl
rm
venv.html
73909
0644
edit
dl
rm
warnings.html
50320
0644
edit
dl
rm
wave.html
29868
0644
edit
dl
rm
weakref.html
65292
0644
edit
dl
rm
webbrowser.html
26901
0644
edit
dl
rm
windows.html
10626
0644
edit
dl
rm
winreg.html
66730
0644
edit
dl
rm
winsound.html
21268
0644
edit
dl
rm
wsgiref.html
94492
0644
edit
dl
rm
xdrlib.html
33751
0644
edit
dl
rm
xml.dom.html
97570
0644
edit
dl
rm
xml.dom.minidom.html
41481
0644
edit
dl
rm
xml.dom.pulldom.html
24214
0644
edit
dl
rm
xml.etree.elementtree.html
135491
0644
edit
dl
rm
xml.html
19261
0644
edit
dl
rm
xml.sax.handler.html
42659
0644
edit
dl
rm
xml.sax.html
25515
0644
edit
dl
rm
xml.sax.reader.html
45869
0644
edit
dl
rm
xml.sax.utils.html
16928
0644
edit
dl
rm
xmlrpc.client.html
71947
0644
edit
dl
rm
xmlrpc.html
8535
0644
edit
dl
rm
xmlrpc.server.html
49195
0644
edit
dl
rm
zipapp.html
45105
0644
edit
dl
rm
zipfile.html
80039
0644
edit
dl
rm
zipimport.html
23052
0644
edit
dl
rm
zlib.html
34557
0644
edit
dl
rm
_dummy_thread.html
9193
0644
edit
dl
rm
_thread.html
22588
0644
edit
dl
rm
__future__.html
15792
0644
edit
dl
rm
__main__.html
9019
0644
edit
dl
rm
Edit:
/usr/share/doc/python3-docs/html/library/asyncio-task.html
(83968B)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>18.5.3. Tasks and coroutines — Python 3.6.7 documentation</title> <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.6.7 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="18.5.4. Transports and protocols (callback based API)" href="asyncio-protocol.html" /> <link rel="prev" title="18.5.2. Event loops" href="asyncio-eventloops.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <link rel="canonical" href="https://docs.python.org/3/library/asyncio-task.html" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head><body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-protocol.html" title="18.5.4. Transports and protocols (callback based API)" accesskey="N">next</a> |</li> <li class="right" > <a href="asyncio-eventloops.html" title="18.5.2. Event loops" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li> <a href="../index.html">3.6.7 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >18. Interprocess Communication and Networking</a> »</li> <li class="nav-item nav-item-3"><a href="asyncio.html" accesskey="U">18.5. <code class="docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O, event loop, coroutines and tasks</a> »</li> <li class="right"> <div class="inline-search" style="display: none" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('.inline-search').show(0);</script> | </li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="tasks-and-coroutines"> <h1>18.5.3. Tasks and coroutines<a class="headerlink" href="#tasks-and-coroutines" title="Permalink to this headline">¶</a></h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.6/Lib/asyncio/tasks.py">Lib/asyncio/tasks.py</a></p> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.6/Lib/asyncio/coroutines.py">Lib/asyncio/coroutines.py</a></p> <div class="section" id="coroutines"> <span id="coroutine"></span><h2>18.5.3.1. Coroutines<a class="headerlink" href="#coroutines" title="Permalink to this headline">¶</a></h2> <p>Coroutines used with <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O, event loop, coroutines and tasks."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> may be implemented using the <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> statement, or by using <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generators</span></a>. The <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> type of coroutine was added in Python 3.5, and is recommended if there is no need to support older Python versions.</p> <p>Generator-based coroutines should be decorated with <a class="reference internal" href="#asyncio.coroutine" title="asyncio.coroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">@asyncio.coroutine</span></code></a>, although this is not strictly enforced. The decorator enables compatibility with <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines, and also serves as documentation. Generator-based coroutines use the <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> syntax introduced in <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0380"><strong>PEP 380</strong></a>, instead of the original <code class="docutils literal notranslate"><span class="pre">yield</span></code> syntax.</p> <p>The word “coroutine”, like the word “generator”, is used for two different (though related) concepts:</p> <ul class="simple"> <li>The function that defines a coroutine (a function definition using <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> or decorated with <code class="docutils literal notranslate"><span class="pre">@asyncio.coroutine</span></code>). If disambiguation is needed we will call this a <em>coroutine function</em> (<a class="reference internal" href="#asyncio.iscoroutinefunction" title="asyncio.iscoroutinefunction"><code class="xref py py-func docutils literal notranslate"><span class="pre">iscoroutinefunction()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>).</li> <li>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 <em>coroutine object</em> (<a class="reference internal" href="#asyncio.iscoroutine" title="asyncio.iscoroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">iscoroutine()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>).</li> </ul> <p>Things a coroutine can do:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">await</span> <span class="pre">future</span></code> or <code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">from</span> <span class="pre">future</span></code> – 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 <code class="docutils literal notranslate"><span class="pre">CancelledError</span></code> exception.) Note that tasks are futures, and everything said about futures also applies to tasks.</li> <li><code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">await</span> <span class="pre">coroutine</span></code> or <code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">from</span> <span class="pre">coroutine</span></code> – wait for another coroutine to produce a result (or raise an exception, which will be propagated). The <code class="docutils literal notranslate"><span class="pre">coroutine</span></code> expression must be a <em>call</em> to another coroutine.</li> <li><code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">expression</span></code> – produce a result to the coroutine that is waiting for this one using <a class="reference internal" href="../reference/expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> or <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">exception</span></code> – raise an exception in the coroutine that is waiting for this one using <a class="reference internal" href="../reference/expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> or <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code>.</li> </ul> <p>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 <code class="docutils literal notranslate"><span class="pre">await</span> <span class="pre">coroutine</span></code> or <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre">coroutine</span></code> from another coroutine (assuming the other coroutine is already running!), or schedule its execution using the <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a> function or the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.create_task" title="asyncio.AbstractEventLoop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.create_task()</span></code></a> method.</p> <p>Coroutines (and tasks) can only run when the event loop is running.</p> <dl class="function"> <dt id="asyncio.coroutine"> <code class="descclassname">@</code><code class="descclassname">asyncio.</code><code class="descname">coroutine</code><a class="headerlink" href="#asyncio.coroutine" title="Permalink to this definition">¶</a></dt> <dd><p>Decorator to mark generator-based coroutines. This enables the generator use <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> to call <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines, and also enables the generator to be called by <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines, for instance using an <a class="reference internal" href="../reference/expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expression.</p> <p>There is no need to decorate <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines themselves.</p> <p>If the generator is not yielded from before it is destroyed, an error message is logged. See <a class="reference internal" href="asyncio-dev.html#asyncio-coroutine-not-scheduled"><span class="std std-ref">Detect coroutines never scheduled</span></a>.</p> </dd></dl> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">In this documentation, some methods are documented as coroutines, even if they are plain Python functions returning a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>. 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 <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a>.</p> </div> <div class="section" id="example-hello-world-coroutine"> <span id="asyncio-hello-world-coroutine"></span><h3>18.5.3.1.1. Example: Hello World coroutine<a class="headerlink" href="#example-hello-world-coroutine" title="Permalink to this headline">¶</a></h3> <p>Example of coroutine displaying <code class="docutils literal notranslate"><span class="pre">"Hello</span> <span class="pre">World"</span></code>:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">hello_world</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Hello World!"</span><span class="p">)</span> <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="c1"># Blocking call which returns when the hello_world() coroutine is done</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">hello_world</span><span class="p">())</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio-hello-world-callback"><span class="std std-ref">Hello World with call_soon()</span></a> example uses the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_soon" title="asyncio.AbstractEventLoop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.call_soon()</span></code></a> method to schedule a callback.</p> </div> </div> <div class="section" id="example-coroutine-displaying-the-current-date"> <span id="asyncio-date-coroutine"></span><h3>18.5.3.1.2. Example: Coroutine displaying the current date<a class="headerlink" href="#example-coroutine-displaying-the-current-date" title="Permalink to this headline">¶</a></h3> <p>Example of coroutine displaying the current date every second during 5 seconds using the <a class="reference internal" href="#asyncio.sleep" title="asyncio.sleep"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sleep()</span></code></a> function:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span> <span class="kn">import</span> <span class="nn">datetime</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">display_date</span><span class="p">(</span><span class="n">loop</span><span class="p">):</span> <span class="n">end_time</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">5.0</span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())</span> <span class="k">if</span> <span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">1.0</span><span class="p">)</span> <span class="o">>=</span> <span class="n">end_time</span><span class="p">:</span> <span class="k">break</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="c1"># Blocking call which returns when the display_date() coroutine is done</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">display_date</span><span class="p">(</span><span class="n">loop</span><span class="p">))</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio-date-callback"><span class="std std-ref">display the current date with call_later()</span></a> example uses a callback with the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_later" title="asyncio.AbstractEventLoop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.call_later()</span></code></a> method.</p> </div> </div> <div class="section" id="example-chain-coroutines"> <h3>18.5.3.1.3. Example: Chain coroutines<a class="headerlink" href="#example-chain-coroutines" title="Permalink to this headline">¶</a></h3> <p>Example chaining coroutines:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">compute</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Compute </span><span class="si">%s</span><span class="s2"> + </span><span class="si">%s</span><span class="s2"> ..."</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">1.0</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">print_sum</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">compute</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"</span><span class="si">%s</span><span class="s2"> + </span><span class="si">%s</span><span class="s2"> = </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">result</span><span class="p">))</span> <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">print_sum</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <p><code class="docutils literal notranslate"><span class="pre">compute()</span></code> is chained to <code class="docutils literal notranslate"><span class="pre">print_sum()</span></code>: <code class="docutils literal notranslate"><span class="pre">print_sum()</span></code> coroutine waits until <code class="docutils literal notranslate"><span class="pre">compute()</span></code> is completed before returning its result.</p> <p>Sequence diagram of the example:</p> <img alt="../_images/tulip_coro.png" class="align-center" src="../_images/tulip_coro.png" /> <p>The “Task” is created by the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.run_until_complete" title="asyncio.AbstractEventLoop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.run_until_complete()</span></code></a> method when it gets a coroutine object instead of a task.</p> <p>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 <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_later" title="asyncio.AbstractEventLoop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.call_later()</span></code></a> to wake up the task in 1 second.</p> </div> </div> <div class="section" id="invalidstateerror"> <h2>18.5.3.2. InvalidStateError<a class="headerlink" href="#invalidstateerror" title="Permalink to this headline">¶</a></h2> <dl class="exception"> <dt id="asyncio.InvalidStateError"> <em class="property">exception </em><code class="descclassname">asyncio.</code><code class="descname">InvalidStateError</code><a class="headerlink" href="#asyncio.InvalidStateError" title="Permalink to this definition">¶</a></dt> <dd><p>The operation is not allowed in this state.</p> </dd></dl> </div> <div class="section" id="timeouterror"> <h2>18.5.3.3. TimeoutError<a class="headerlink" href="#timeouterror" title="Permalink to this headline">¶</a></h2> <dl class="exception"> <dt id="asyncio.TimeoutError"> <em class="property">exception </em><code class="descclassname">asyncio.</code><code class="descname">TimeoutError</code><a class="headerlink" href="#asyncio.TimeoutError" title="Permalink to this definition">¶</a></dt> <dd><p>The operation exceeded the given deadline.</p> </dd></dl> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">This exception is different from the builtin <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> exception!</p> </div> </div> <div class="section" id="future"> <h2>18.5.3.4. Future<a class="headerlink" href="#future" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="asyncio.Future"> <em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">Future</code><span class="sig-paren">(</span><em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future" title="Permalink to this definition">¶</a></dt> <dd><p>This class is <em>almost</em> compatible with <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a>.</p> <p>Differences:</p> <ul class="simple"> <li><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">result()</span></code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exception()</span></code></a> do not take a timeout argument and raise an exception when the future isn’t done yet.</li> <li>Callbacks registered with <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_done_callback()</span></code></a> are always called via the event loop’s <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_soon" title="asyncio.AbstractEventLoop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon()</span></code></a>.</li> <li>This class is not compatible with the <a class="reference internal" href="concurrent.futures.html#concurrent.futures.wait" title="concurrent.futures.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait()</span></code></a> and <a class="reference internal" href="concurrent.futures.html#concurrent.futures.as_completed" title="concurrent.futures.as_completed"><code class="xref py py-func docutils literal notranslate"><span class="pre">as_completed()</span></code></a> functions in the <a class="reference internal" href="concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code></a> package.</li> </ul> <p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p> <dl class="method"> <dt id="asyncio.Future.cancel"> <code class="descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancel" title="Permalink to this definition">¶</a></dt> <dd><p>Cancel the future and schedule callbacks.</p> <p>If the future is already done or cancelled, return <code class="docutils literal notranslate"><span class="pre">False</span></code>. Otherwise, change the future’s state to cancelled, schedule the callbacks and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.cancelled"> <code class="descname">cancelled</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancelled" title="Permalink to this definition">¶</a></dt> <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the future was cancelled.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.done"> <code class="descname">done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.done" title="Permalink to this definition">¶</a></dt> <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the future is done.</p> <p>Done means either that a result / exception are available, or that the future was cancelled.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.result"> <code class="descname">result</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.result" title="Permalink to this definition">¶</a></dt> <dd><p>Return the result this future represents.</p> <p>If the future has been cancelled, raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code>. If the future’s result isn’t yet available, raises <a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>. If the future is done and has an exception set, this exception is raised.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.exception"> <code class="descname">exception</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.exception" title="Permalink to this definition">¶</a></dt> <dd><p>Return the exception that was set on this future.</p> <p>The exception (or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no exception was set) is returned only if the future is done. If the future has been cancelled, raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code>. If the future isn’t done yet, raises <a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.add_done_callback"> <code class="descname">add_done_callback</code><span class="sig-paren">(</span><em>fn</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.add_done_callback" title="Permalink to this definition">¶</a></dt> <dd><p>Add a callback to be run when the future becomes done.</p> <p>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 <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_soon" title="asyncio.AbstractEventLoop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon()</span></code></a>.</p> <p><a class="reference internal" href="asyncio-eventloop.html#asyncio-pass-keywords"><span class="std std-ref">Use functools.partial to pass parameters to the callback</span></a>. For example, <code class="docutils literal notranslate"><span class="pre">fut.add_done_callback(functools.partial(print,</span> <span class="pre">"Future:",</span> <span class="pre">flush=True))</span></code> will call <code class="docutils literal notranslate"><span class="pre">print("Future:",</span> <span class="pre">fut,</span> <span class="pre">flush=True)</span></code>.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.remove_done_callback"> <code class="descname">remove_done_callback</code><span class="sig-paren">(</span><em>fn</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.remove_done_callback" title="Permalink to this definition">¶</a></dt> <dd><p>Remove all instances of a callback from the “call when done” list.</p> <p>Returns the number of callbacks removed.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.set_result"> <code class="descname">set_result</code><span class="sig-paren">(</span><em>result</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_result" title="Permalink to this definition">¶</a></dt> <dd><p>Mark the future done and set its result.</p> <p>If the future is already done when this method is called, raises <a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Future.set_exception"> <code class="descname">set_exception</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_exception" title="Permalink to this definition">¶</a></dt> <dd><p>Mark the future done and set an exception.</p> <p>If the future is already done when this method is called, raises <a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>.</p> </dd></dl> </dd></dl> <div class="section" id="example-future-with-run-until-complete"> <h3>18.5.3.4.1. Example: Future with run_until_complete()<a class="headerlink" href="#example-future-with-run-until-complete" title="Permalink to this headline">¶</a></h3> <p>Example combining a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> and a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine function</span></a>:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">):</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">future</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="s1">'Future is done!'</span><span class="p">)</span> <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span><span class="p">()</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">))</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">future</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">())</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <p>The coroutine function is responsible for the computation (which takes 1 second) and it stores the result into the future. The <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.run_until_complete" title="asyncio.AbstractEventLoop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_until_complete()</span></code></a> method waits for the completion of the future.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.run_until_complete" title="asyncio.AbstractEventLoop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_until_complete()</span></code></a> method uses internally the <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_done_callback()</span></code></a> method to be notified when the future is done.</p> </div> </div> <div class="section" id="example-future-with-run-forever"> <h3>18.5.3.4.2. Example: Future with run_forever()<a class="headerlink" href="#example-future-with-run-forever" title="Permalink to this headline">¶</a></h3> <p>The previous example can be written differently using the <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.add_done_callback()</span></code></a> method to describe explicitly the control flow:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">):</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">future</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="s1">'Future is done!'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">got_result</span><span class="p">(</span><span class="n">future</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">())</span> <span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span> <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span><span class="p">()</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">))</span> <span class="n">future</span><span class="o">.</span><span class="n">add_done_callback</span><span class="p">(</span><span class="n">got_result</span><span class="p">)</span> <span class="k">try</span><span class="p">:</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span> <span class="k">finally</span><span class="p">:</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <p>In this example, the future is used to link <code class="docutils literal notranslate"><span class="pre">slow_operation()</span></code> to <code class="docutils literal notranslate"><span class="pre">got_result()</span></code>: when <code class="docutils literal notranslate"><span class="pre">slow_operation()</span></code> is done, <code class="docutils literal notranslate"><span class="pre">got_result()</span></code> is called with the result.</p> </div> </div> <div class="section" id="task"> <h2>18.5.3.5. Task<a class="headerlink" href="#task" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="asyncio.Task"> <em class="property">class </em><code class="descclassname">asyncio.</code><code class="descname">Task</code><span class="sig-paren">(</span><em>coro</em>, <em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task" title="Permalink to this definition">¶</a></dt> <dd><p>Schedule the execution of a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>: wrap it in a future. A task is a subclass of <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>.</p> <p>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.</p> <p>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.</p> <p>The cancellation of a task is different from the cancelation of a future. Calling <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> will throw a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> to the wrapped coroutine. <a class="reference internal" href="#asyncio.Future.cancelled" title="asyncio.Future.cancelled"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancelled()</span></code></a> only returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the wrapped coroutine did not catch the <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception, or raised a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception.</p> <p>If a pending task is destroyed, the execution of its wrapped <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a> did not complete. It is probably a bug and a warning is logged: see <a class="reference internal" href="asyncio-dev.html#asyncio-pending-task-destroyed"><span class="std std-ref">Pending task destroyed</span></a>.</p> <p>Don’t directly create <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> instances: use the <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a> function or the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.create_task" title="asyncio.AbstractEventLoop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.create_task()</span></code></a> method.</p> <p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p> <dl class="classmethod"> <dt id="asyncio.Task.all_tasks"> <em class="property">classmethod </em><code class="descname">all_tasks</code><span class="sig-paren">(</span><em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.all_tasks" title="Permalink to this definition">¶</a></dt> <dd><p>Return a set of all tasks for an event loop.</p> <p>By default all tasks for the current event loop are returned.</p> </dd></dl> <dl class="classmethod"> <dt id="asyncio.Task.current_task"> <em class="property">classmethod </em><code class="descname">current_task</code><span class="sig-paren">(</span><em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.current_task" title="Permalink to this definition">¶</a></dt> <dd><p>Return the currently running task in an event loop or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p> <p>By default the current task for the current event loop is returned.</p> <p><code class="docutils literal notranslate"><span class="pre">None</span></code> is returned when called not in the context of a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Task.cancel"> <code class="descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.cancel" title="Permalink to this definition">¶</a></dt> <dd><p>Request that this task cancel itself.</p> <p>This arranges for a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> 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.</p> <p>Unlike <a class="reference internal" href="#asyncio.Future.cancel" title="asyncio.Future.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.cancel()</span></code></a>, 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.</p> <p>Immediately after this method is called, <a class="reference internal" href="#asyncio.Future.cancelled" title="asyncio.Future.cancelled"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancelled()</span></code></a> will not return <code class="docutils literal notranslate"><span class="pre">True</span></code> (unless the task was already cancelled). A task will be marked as cancelled when the wrapped coroutine terminates with a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception (even if <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> was not called).</p> </dd></dl> <dl class="method"> <dt id="asyncio.Task.get_stack"> <code class="descname">get_stack</code><span class="sig-paren">(</span><em>*</em>, <em>limit=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.get_stack" title="Permalink to this definition">¶</a></dt> <dd><p>Return the list of stack frames for this task’s coroutine.</p> <p>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.</p> <p>The frames are always ordered from oldest to newest.</p> <p>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.)</p> <p>For reasons beyond our control, only one stack frame is returned for a suspended coroutine.</p> </dd></dl> <dl class="method"> <dt id="asyncio.Task.print_stack"> <code class="descname">print_stack</code><span class="sig-paren">(</span><em>*</em>, <em>limit=None</em>, <em>file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.print_stack" title="Permalink to this definition">¶</a></dt> <dd><p>Print the stack or traceback for this task’s coroutine.</p> <p>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.</p> </dd></dl> </dd></dl> <div class="section" id="example-parallel-execution-of-tasks"> <h3>18.5.3.5.1. Example: Parallel execution of tasks<a class="headerlink" href="#example-parallel-execution-of-tasks" title="Permalink to this headline">¶</a></h3> <p>Example executing 3 tasks (A, B, C) in parallel:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span> <span class="n">f</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">number</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Task </span><span class="si">%s</span><span class="s2">: Compute factorial(</span><span class="si">%s</span><span class="s2">)..."</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">i</span><span class="p">))</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">f</span> <span class="o">*=</span> <span class="n">i</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Task </span><span class="si">%s</span><span class="s2">: factorial(</span><span class="si">%s</span><span class="s2">) = </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">number</span><span class="p">,</span> <span class="n">f</span><span class="p">))</span> <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span> <span class="n">factorial</span><span class="p">(</span><span class="s2">"A"</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="n">factorial</span><span class="p">(</span><span class="s2">"B"</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">factorial</span><span class="p">(</span><span class="s2">"C"</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">))</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <p>Output:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Task</span> <span class="n">A</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span> <span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span> <span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span> <span class="n">Task</span> <span class="n">A</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">=</span> <span class="mi">2</span> <span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">...</span> <span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">...</span> <span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="o">=</span> <span class="mi">6</span> <span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span><span class="o">...</span> <span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="o">=</span> <span class="mi">24</span> </pre></div> </div> <p>A task is automatically scheduled for execution when it is created. The event loop stops when all tasks are done.</p> </div> </div> <div class="section" id="task-functions"> <h2>18.5.3.6. Task functions<a class="headerlink" href="#task-functions" title="Permalink to this headline">¶</a></h2> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">In the functions below, the optional <em>loop</em> 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.</p> </div> <dl class="function"> <dt id="asyncio.as_completed"> <code class="descclassname">asyncio.</code><code class="descname">as_completed</code><span class="sig-paren">(</span><em>fs</em>, <em>*</em>, <em>loop=None</em>, <em>timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.as_completed" title="Permalink to this definition">¶</a></dt> <dd><p>Return an iterator whose values, when waited for, are <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> instances.</p> <p>Raises <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.TimeoutError</span></code></a> if the timeout occurs before all Futures are done.</p> <p>Example:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">as_completed</span><span class="p">(</span><span class="n">fs</span><span class="p">):</span> <span class="n">result</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">f</span> <span class="c1"># The 'yield from' may raise</span> <span class="c1"># Use result</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The futures <code class="docutils literal notranslate"><span class="pre">f</span></code> are not necessarily members of fs.</p> </div> </dd></dl> <dl class="function"> <dt id="asyncio.ensure_future"> <code class="descclassname">asyncio.</code><code class="descname">ensure_future</code><span class="sig-paren">(</span><em>coro_or_future</em>, <em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.ensure_future" title="Permalink to this definition">¶</a></dt> <dd><p>Schedule the execution of a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a>: wrap it in a future. Return a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object.</p> <p>If the argument is a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>, it is returned directly.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 3.4.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 3.5.1: </span>The function accepts any <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.</p> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.create_task" title="asyncio.AbstractEventLoop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.create_task()</span></code></a> method.</p> </div> </dd></dl> <dl class="function"> <dt id="asyncio.async"> <code class="descclassname">asyncio.</code><code class="descname">async</code><span class="sig-paren">(</span><em>coro_or_future</em>, <em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.async" title="Permalink to this definition">¶</a></dt> <dd><p>A deprecated alias to <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a>.</p> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 3.4.4.</span></p> </div> </dd></dl> <dl class="function"> <dt id="asyncio.wrap_future"> <code class="descclassname">asyncio.</code><code class="descname">wrap_future</code><span class="sig-paren">(</span><em>future</em>, <em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wrap_future" title="Permalink to this definition">¶</a></dt> <dd><p>Wrap a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> object in a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> object.</p> </dd></dl> <dl class="function"> <dt id="asyncio.gather"> <code class="descclassname">asyncio.</code><code class="descname">gather</code><span class="sig-paren">(</span><em>*coros_or_futures</em>, <em>loop=None</em>, <em>return_exceptions=False</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.gather" title="Permalink to this definition">¶</a></dt> <dd><p>Return a future aggregating results from the given coroutine objects or futures.</p> <p>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 <em>return_exceptions</em> 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.</p> <p>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 <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> – the outer Future is <em>not</em> cancelled in this case. (This is to prevent the cancellation of one child to cause other children to be cancelled.)</p> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 3.6.6: </span>If the <em>gather</em> itself is cancelled, the cancellation is propagated regardless of <em>return_exceptions</em>.</p> </div> </dd></dl> <dl class="function"> <dt id="asyncio.iscoroutine"> <code class="descclassname">asyncio.</code><code class="descname">iscoroutine</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.iscoroutine" title="Permalink to this definition">¶</a></dt> <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>obj</em> is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a>, which may be based on a generator or an <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutine.</p> </dd></dl> <dl class="function"> <dt id="asyncio.iscoroutinefunction"> <code class="descclassname">asyncio.</code><code class="descname">iscoroutinefunction</code><span class="sig-paren">(</span><em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.iscoroutinefunction" title="Permalink to this definition">¶</a></dt> <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>func</em> is determined to be a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine function</span></a>, which may be a decorated generator function or an <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function.</p> </dd></dl> <dl class="function"> <dt id="asyncio.run_coroutine_threadsafe"> <code class="descclassname">asyncio.</code><code class="descname">run_coroutine_threadsafe</code><span class="sig-paren">(</span><em>coro</em>, <em>loop</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.run_coroutine_threadsafe" title="Permalink to this definition">¶</a></dt> <dd><p>Submit a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a> to a given event loop.</p> <p>Return a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> to access the result.</p> <p>This function is meant to be called from a different thread than the one where the event loop is running. Usage:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Create a coroutine</span> <span class="n">coro</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">result</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="c1"># Submit the coroutine to a given loop</span> <span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">run_coroutine_threadsafe</span><span class="p">(</span><span class="n">coro</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span> <span class="c1"># Wait for the result with an optional timeout argument</span> <span class="k">assert</span> <span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span> <span class="o">==</span> <span class="mi">3</span> </pre></div> </div> <p>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:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span> <span class="n">result</span> <span class="o">=</span> <span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span> <span class="k">except</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">TimeoutError</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'The coroutine took too long, cancelling the task...'</span><span class="p">)</span> <span class="n">future</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'The coroutine raised an exception: </span><span class="si">{!r}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">exc</span><span class="p">))</span> <span class="k">else</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'The coroutine returned: </span><span class="si">{!r}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">result</span><span class="p">))</span> </pre></div> </div> <p>See the <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">concurrency and multithreading</span></a> section of the documentation.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Unlike other functions from the module, <a class="reference internal" href="#asyncio.run_coroutine_threadsafe" title="asyncio.run_coroutine_threadsafe"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_coroutine_threadsafe()</span></code></a> requires the <em>loop</em> argument to be passed explicitly.</p> </div> <div class="versionadded"> <p><span class="versionmodified">New in version 3.5.1.</span></p> </div> </dd></dl> <dl class="function"> <dt id="asyncio.sleep"> <em class="property">coroutine </em><code class="descclassname">asyncio.</code><code class="descname">sleep</code><span class="sig-paren">(</span><em>delay</em>, <em>result=None</em>, <em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.sleep" title="Permalink to this definition">¶</a></dt> <dd><p>Create a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a> that completes after a given time (in seconds). If <em>result</em> is provided, it is produced to the caller when the coroutine completes.</p> <p>The resolution of the sleep depends on the <a class="reference internal" href="asyncio-eventloop.html#asyncio-delayed-calls"><span class="std std-ref">granularity of the event loop</span></a>.</p> <p>This function is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>.</p> </dd></dl> <dl class="function"> <dt id="asyncio.shield"> <em class="property">coroutine </em><code class="descclassname">asyncio.</code><code class="descname">shield</code><span class="sig-paren">(</span><em>arg</em>, <em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.shield" title="Permalink to this definition">¶</a></dt> <dd><p>Wait for a future, shielding it from cancellation.</p> <p>The statement:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">shield</span><span class="p">(</span><span class="n">something</span><span class="p">())</span> </pre></div> </div> <p>is exactly equivalent to the statement:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">something</span><span class="p">()</span> </pre></div> </div> <p><em>except</em> that if the coroutine containing it is cancelled, the task running in <code class="docutils literal notranslate"><span class="pre">something()</span></code> is not cancelled. From the point of view of <code class="docutils literal notranslate"><span class="pre">something()</span></code>, the cancellation did not happen. But its caller is still cancelled, so the yield-from expression still raises <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a>. Note: If <code class="docutils literal notranslate"><span class="pre">something()</span></code> is cancelled by other means this will still cancel <code class="docutils literal notranslate"><span class="pre">shield()</span></code>.</p> <p>If you want to completely ignore cancellation (not recommended) you can combine <code class="docutils literal notranslate"><span class="pre">shield()</span></code> with a try/except clause, as follows:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span> <span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">shield</span><span class="p">(</span><span class="n">something</span><span class="p">())</span> <span class="k">except</span> <span class="n">CancelledError</span><span class="p">:</span> <span class="n">res</span> <span class="o">=</span> <span class="kc">None</span> </pre></div> </div> </dd></dl> <dl class="function"> <dt id="asyncio.wait"> <em class="property">coroutine </em><code class="descclassname">asyncio.</code><code class="descname">wait</code><span class="sig-paren">(</span><em>futures</em>, <em>*</em>, <em>loop=None</em>, <em>timeout=None</em>, <em>return_when=ALL_COMPLETED</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wait" title="Permalink to this definition">¶</a></dt> <dd><p>Wait for the Futures and coroutine objects given by the sequence <em>futures</em> to complete. Coroutines will be wrapped in Tasks. Returns two sets of <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>: (done, pending).</p> <p>The sequence <em>futures</em> must not be empty.</p> <p><em>timeout</em> can be used to control the maximum number of seconds to wait before returning. <em>timeout</em> can be an int or float. If <em>timeout</em> is not specified or <code class="docutils literal notranslate"><span class="pre">None</span></code>, there is no limit to the wait time.</p> <p><em>return_when</em> indicates when this function should return. It must be one of the following constants of the <a class="reference internal" href="concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code></a> module:</p> <table border="1" class="docutils"> <colgroup> <col width="42%" /> <col width="58%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Constant</th> <th class="head">Description</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">FIRST_COMPLETED</span></code></td> <td>The function will return when any future finishes or is cancelled.</td> </tr> <tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">FIRST_EXCEPTION</span></code></td> <td>The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to <code class="xref py py-const docutils literal notranslate"><span class="pre">ALL_COMPLETED</span></code>.</td> </tr> <tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ALL_COMPLETED</span></code></td> <td>The function will return when all futures finish or are cancelled.</td> </tr> </tbody> </table> <p>This function is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>.</p> <p>Usage:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">done</span><span class="p">,</span> <span class="n">pending</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">fs</span><span class="p">)</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">This does not raise <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.TimeoutError</span></code></a>! Futures that aren’t done when the timeout occurs are returned in the second set.</p> </div> </dd></dl> <dl class="function"> <dt id="asyncio.wait_for"> <em class="property">coroutine </em><code class="descclassname">asyncio.</code><code class="descname">wait_for</code><span class="sig-paren">(</span><em>fut</em>, <em>timeout</em>, <em>*</em>, <em>loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wait_for" title="Permalink to this definition">¶</a></dt> <dd><p>Wait for the single <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> or <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a> to complete with timeout. If <em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, block until the future completes.</p> <p>Coroutine will be wrapped in <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p> <p>Returns result of the Future or coroutine. When a timeout occurs, it cancels the task and raises <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.TimeoutError</span></code></a>. To avoid the task cancellation, wrap it in <a class="reference internal" href="#asyncio.shield" title="asyncio.shield"><code class="xref py py-func docutils literal notranslate"><span class="pre">shield()</span></code></a>.</p> <p>If the wait is cancelled, the future <em>fut</em> is also cancelled.</p> <p>This function is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>, usage:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="mf">60.0</span><span class="p">)</span> </pre></div> </div> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 3.4.3: </span>If the wait is cancelled, the future <em>fut</em> is now also cancelled.</p> </div> </dd></dl> </div> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">18.5.3. Tasks and coroutines</a><ul> <li><a class="reference internal" href="#coroutines">18.5.3.1. Coroutines</a><ul> <li><a class="reference internal" href="#example-hello-world-coroutine">18.5.3.1.1. Example: Hello World coroutine</a></li> <li><a class="reference internal" href="#example-coroutine-displaying-the-current-date">18.5.3.1.2. Example: Coroutine displaying the current date</a></li> <li><a class="reference internal" href="#example-chain-coroutines">18.5.3.1.3. Example: Chain coroutines</a></li> </ul> </li> <li><a class="reference internal" href="#invalidstateerror">18.5.3.2. InvalidStateError</a></li> <li><a class="reference internal" href="#timeouterror">18.5.3.3. TimeoutError</a></li> <li><a class="reference internal" href="#future">18.5.3.4. Future</a><ul> <li><a class="reference internal" href="#example-future-with-run-until-complete">18.5.3.4.1. Example: Future with run_until_complete()</a></li> <li><a class="reference internal" href="#example-future-with-run-forever">18.5.3.4.2. Example: Future with run_forever()</a></li> </ul> </li> <li><a class="reference internal" href="#task">18.5.3.5. Task</a><ul> <li><a class="reference internal" href="#example-parallel-execution-of-tasks">18.5.3.5.1. Example: Parallel execution of tasks</a></li> </ul> </li> <li><a class="reference internal" href="#task-functions">18.5.3.6. Task functions</a></li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="asyncio-eventloops.html" title="previous chapter">18.5.2. Event loops</a></p> <h4>Next topic</h4> <p class="topless"><a href="asyncio-protocol.html" title="next chapter">18.5.4. Transports and protocols (callback based API)</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li> <a href="https://github.com/python/cpython/blob/3.6/Doc/library/asyncio-task.rst" rel="nofollow">Show Source </a> </li> </ul> </div> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="asyncio-protocol.html" title="18.5.4. Transports and protocols (callback based API)" >next</a> |</li> <li class="right" > <a href="asyncio-eventloops.html" title="18.5.2. Event loops" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li> <a href="../index.html">3.6.7 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="ipc.html" >18. Interprocess Communication and Networking</a> »</li> <li class="nav-item nav-item-3"><a href="asyncio.html" >18.5. <code class="docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O, event loop, coroutines and tasks</a> »</li> <li class="right"> <div class="inline-search" style="display: none" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('.inline-search').show(0);</script> | </li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Dec 18, 2023. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6. </div> </body> </html>
Save
cmd:
run