-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncio-task.html
More file actions
988 lines (918 loc) · 89.5 KB
/
asyncio-task.html
File metadata and controls
988 lines (918 loc) · 89.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
<!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" lang="zh_TW">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>19.5.3. Tasks and coroutines — Python 3.7.0 說明文件</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/translations.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.7.0 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="19.5.4. Transports and protocols (callback based API)" href="asyncio-protocol.html" />
<link rel="prev" title="19.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>
<script type="text/javascript" src="../_static/switchers.js"></script>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="asyncio-protocol.html" title="19.5.4. Transports and protocols (callback based API)"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="asyncio-eventloops.html" title="19.5.2. Event loops"
accesskey="P">上一頁</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>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python 標準函式庫 (Standard Library)</a> »</li>
<li class="nav-item nav-item-2"><a href="ipc.html" >19. Interprocess Communication and Networking</a> »</li>
<li class="nav-item nav-item-3"><a href="asyncio.html" accesskey="U">19.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>19.5.3. Tasks and coroutines<a class="headerlink" href="#tasks-and-coroutines" title="本標題的永久連結">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/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.7/Lib/asyncio/coroutines.py">Lib/asyncio/coroutines.py</a></p>
<div class="section" id="coroutines">
<span id="coroutine"></span><h2>19.5.3.1. Coroutines<a class="headerlink" href="#coroutines" title="本標題的永久連結">¶</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="本定義的永久連結">¶</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">備註</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>
<dl class="function">
<dt id="asyncio.run">
<code class="descclassname">asyncio.</code><code class="descname">run</code><span class="sig-paren">(</span><em>coro</em>, <em>*</em>, <em>debug=False</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.run" title="本定義的永久連結">¶</a></dt>
<dd><p>This function runs the passed coroutine, taking care of
managing the asyncio event loop and finalizing asynchronous
generators.</p>
<p>This function cannot be called when another asyncio event loop is
running in the same thread.</p>
<p>If debug is True, the event loop will be run in debug mode.</p>
<p>This function always creates a new event loop and closes it at
the end. It should be used as a main entry point for asyncio
programs, and should ideally only be called once.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 版新加入: </span><strong>Important:</strong> this has been been added to asyncio in Python 3.7
on a <a class="reference internal" href="../glossary.html#term-provisional-api"><span class="xref std std-term">provisional basis</span></a>.</p>
</div>
</dd></dl>
<div class="section" id="example-hello-world-coroutine">
<span id="asyncio-hello-world-coroutine"></span><h3>19.5.3.1.1. Example: Hello World coroutine<a class="headerlink" href="#example-hello-world-coroutine" title="本標題的永久連結">¶</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">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">hello_world</span><span class="p">())</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">也參考</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>19.5.3.1.2. Example: Coroutine displaying the current date<a class="headerlink" href="#example-coroutine-displaying-the-current-date" title="本標題的永久連結">¶</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="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_running_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">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">display_date</span><span class="p">())</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">也參考</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>19.5.3.1.3. Example: Chain coroutines<a class="headerlink" href="#example-chain-coroutines" title="本標題的永久連結">¶</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>19.5.3.2. InvalidStateError<a class="headerlink" href="#invalidstateerror" title="本標題的永久連結">¶</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="本定義的永久連結">¶</a></dt>
<dd><p>The operation is not allowed in this state.</p>
</dd></dl>
</div>
<div class="section" id="timeouterror">
<h2>19.5.3.3. TimeoutError<a class="headerlink" href="#timeouterror" title="本標題的永久連結">¶</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="本定義的永久連結">¶</a></dt>
<dd><p>The operation exceeded the given deadline.</p>
</dd></dl>
<div class="admonition note">
<p class="first admonition-title">備註</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>19.5.3.4. Future<a class="headerlink" href="#future" title="本標題的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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>callback</em>, <em>*</em>, <em>context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.add_done_callback" title="本定義的永久連結">¶</a></dt>
<dd><p>Add a callback to be run when the future becomes done.</p>
<p>The <em>callback</em> 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>An optional keyword-only <em>context</em> argument allows specifying a custom
<a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>callback</em> to run in. The current
context is used when no <em>context</em> is provided.</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>
<div class="versionchanged">
<p><span class="versionmodified">3.7 版更變: </span>The <em>context</em> keyword-only parameter was added. See <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a>
for more details.</p>
</div>
</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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>
<dl class="method">
<dt id="asyncio.Future.get_loop">
<code class="descname">get_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.get_loop" title="本定義的永久連結">¶</a></dt>
<dd><p>Return the event loop the future object is bound to.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 版新加入.</span></p>
</div>
</dd></dl>
</dd></dl>
<div class="section" id="example-future-with-run-until-complete">
<h3>19.5.3.4.1. Example: Future with run_until_complete()<a class="headerlink" href="#example-future-with-run-until-complete" title="本標題的永久連結">¶</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">備註</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>19.5.3.4.2. Example: Future with run_forever()<a class="headerlink" href="#example-future-with-run-forever" title="本標題的永久連結">¶</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>19.5.3.5. Task<a class="headerlink" href="#task" title="本標題的永久連結">¶</a></h2>
<dl class="function">
<dt id="asyncio.create_task">
<code class="descclassname">asyncio.</code><code class="descname">create_task</code><span class="sig-paren">(</span><em>coro</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.create_task" title="本定義的永久連結">¶</a></dt>
<dd><p>Wrap a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a> <em>coro</em> into a task and schedule
its execution. Return the task object.</p>
<p>The task is executed in <a class="reference internal" href="asyncio-eventloops.html#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a> context,
<a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised if there is no running loop in
current thread.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 版新加入.</span></p>
</div>
</dd></dl>
<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="本定義的永久連結">¶</a></dt>
<dd><p>A unit for concurrent running of <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutines</span></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 cancellation 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.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</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>Tasks support the <a class="reference internal" href="contextvars.html#module-contextvars" title="contextvars: Context Variables"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code></a> module. When a Task
is created it copies the current context and later runs its coroutine
in the copied context. See <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> for more details.</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>
<div class="versionchanged">
<p><span class="versionmodified">3.7 版更變: </span>Added support for the <a class="reference internal" href="contextvars.html#module-contextvars" title="contextvars: Context Variables"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code></a> module.</p>
</div>
<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="本定義的永久連結">¶</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.
If <em>loop</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="asyncio-eventloops.html#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop()</span></code></a> function
is used to get the current loop.</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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>19.5.3.5.1. Example: Parallel execution of tasks<a class="headerlink" href="#example-parallel-execution-of-tasks" title="本標題的永久連結">¶</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>19.5.3.6. Task functions<a class="headerlink" href="#task-functions" title="本標題的永久連結">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">備註</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.current_task">
<code class="descclassname">asyncio.</code><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.current_task" title="本定義的永久連結">¶</a></dt>
<dd><p>Return the current running <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> instance or <code class="docutils literal notranslate"><span class="pre">None</span></code>, if
no task is running.</p>
<p>If <em>loop</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> <a class="reference internal" href="asyncio-eventloops.html#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a> is used to get
the current loop.</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 版新加入.</span></p>
</div>
</dd></dl>
<dl class="function">
<dt id="asyncio.all_tasks">
<code class="descclassname">asyncio.</code><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.all_tasks" title="本定義的永久連結">¶</a></dt>
<dd><p>Return a set of <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> objects created for the loop.</p>
<p>If <em>loop</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="asyncio-eventloops.html#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a> is used for getting
current loop (contrary to the deprecated <a class="reference internal" href="#asyncio.Task.all_tasks" title="asyncio.Task.all_tasks"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Task.all_tasks()</span></code></a> method
that uses <a class="reference internal" href="asyncio-eventloops.html#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop()</span></code></a>.)</p>
<div class="versionadded">
<p><span class="versionmodified">3.7 版新加入.</span></p>
</div>
</dd></dl>
<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="本定義的永久連結">¶</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">await</span> <span class="n">f</span> <span class="c1"># The 'await' may raise</span>
<span class="c1"># Use result</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">備註</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="本定義的永久連結">¶</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">3.4.4 版新加入.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">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 note">
<p class="first admonition-title">備註</p>
<p class="last"><a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</span></code></a> (added in Python 3.7) is the preferable way
for spawning new tasks.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">也參考</p>
<p class="last">The <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</span></code></a> function and
<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.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="本定義的永久連結">¶</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="本定義的永久連結">¶</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">3.7.0 版更變: </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="本定義的永久連結">¶</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="本定義的永久連結">¶</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="本定義的永久連結">¶</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">備註</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">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="本定義的永久連結">¶</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="本定義的永久連結">¶</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">await</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">await</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">await</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="本定義的永久連結">¶</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">描述</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>Unlike <a class="reference internal" href="#asyncio.wait_for" title="asyncio.wait_for"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait_for()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">wait()</span></code> will not cancel the futures
when a timeout occurs.</p>
<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">await</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">備註</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="本定義的永久連結">¶</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>. The function will wait until
the future is actually cancelled, so the total wait time may exceed
the <em>timeout</em>.</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">await</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">3.4.3 版更變: </span>If the wait is cancelled, the future <em>fut</em> is now also cancelled.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">3.7 版更變: </span>When <em>fut</em> is cancelled due to a timeout, <code class="docutils literal notranslate"><span class="pre">wait_for</span></code> now waits
for <em>fut</em> to be cancelled. Previously,
it raised <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> immediately.</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">目錄</a></h3>
<ul>
<li><a class="reference internal" href="#">19.5.3. Tasks and coroutines</a><ul>
<li><a class="reference internal" href="#coroutines">19.5.3.1. Coroutines</a><ul>
<li><a class="reference internal" href="#example-hello-world-coroutine">19.5.3.1.1. Example: Hello World coroutine</a></li>
<li><a class="reference internal" href="#example-coroutine-displaying-the-current-date">19.5.3.1.2. Example: Coroutine displaying the current date</a></li>
<li><a class="reference internal" href="#example-chain-coroutines">19.5.3.1.3. Example: Chain coroutines</a></li>
</ul>
</li>
<li><a class="reference internal" href="#invalidstateerror">19.5.3.2. InvalidStateError</a></li>
<li><a class="reference internal" href="#timeouterror">19.5.3.3. TimeoutError</a></li>
<li><a class="reference internal" href="#future">19.5.3.4. Future</a><ul>
<li><a class="reference internal" href="#example-future-with-run-until-complete">19.5.3.4.1. Example: Future with run_until_complete()</a></li>
<li><a class="reference internal" href="#example-future-with-run-forever">19.5.3.4.2. Example: Future with run_forever()</a></li>
</ul>
</li>
<li><a class="reference internal" href="#task">19.5.3.5. Task</a><ul>
<li><a class="reference internal" href="#example-parallel-execution-of-tasks">19.5.3.5.1. Example: Parallel execution of tasks</a></li>
</ul>
</li>
<li><a class="reference internal" href="#task-functions">19.5.3.6. Task functions</a></li>
</ul>
</li>
</ul>
<h4>上個主題</h4>
<p class="topless"><a href="asyncio-eventloops.html"
title="上一章">19.5.2. Event loops</a></p>
<h4>下個主題</h4>
<p class="topless"><a href="asyncio-protocol.html"
title="下一章">19.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.7/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>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="asyncio-protocol.html" title="19.5.4. Transports and protocols (callback based API)"
>下一頁</a> |</li>
<li class="right" >
<a href="asyncio-eventloops.html" title="19.5.2. Event loops"
>上一頁</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>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python 標準函式庫 (Standard Library)</a> »</li>
<li class="nav-item nav-item-2"><a href="ipc.html" >19. Interprocess Communication and Networking</a> »</li>
<li class="nav-item nav-item-3"><a href="asyncio.html" >19.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-2018, 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 8月 22, 2018.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.7.
</div>
</body>
</html>