用法:
awaitable asyncio.gather(*aws, return_exceptions=False)
在
aws
序列concurrently
中運行等待對象。如果
aws
中的任何等待是協程,它會自動安排為任務。如果所有可等待對象都成功完成,則結果是返回值的聚合列表。結果值的順序對應於
aws
中等待的順序。如果
return_exceptions
是False
(默認),第一個引發的異常會立即傳播到等待的任務gather()
.其他待辦事項aws
序列不會被取消並將繼續運行。如果
return_exceptions
是True
,則將異常視為成功結果,並在結果列表中聚合。如果
gather()
是cancelled
,則所有提交的等待項(尚未完成)也是cancelled
。如果有任何任務或未來來自
aws
序列是cancelled
, 它被視為提升CancelledError
- 這gather()
電話是不是在這種情況下取消。這是為了防止取消一個已提交的 Task/Future 導致其他 Tasks/Future 被取消。在 3.10 版中更改:刪除了
loop
範圍。例子:
import asyncio async def factorial(name, number): f = 1 for i in range(2, number + 1): print(f"Task {name}: Compute factorial({number}), currently i={i}...") await asyncio.sleep(1) f *= i print(f"Task {name}: factorial({number}) = {f}") return f async def main(): # Schedule three calls *concurrently*: L = await asyncio.gather( factorial("A", 2), factorial("B", 3), factorial("C", 4), ) print(L) asyncio.run(main()) # Expected output: # # Task A: Compute factorial(2), currently i=2... # Task B: Compute factorial(3), currently i=2... # Task C: Compute factorial(4), currently i=2... # Task A: factorial(2) = 2 # Task B: Compute factorial(3), currently i=3... # Task C: Compute factorial(4), currently i=3... # Task B: factorial(3) = 6 # Task C: Compute factorial(4), currently i=4... # Task C: factorial(4) = 24 # [2, 6, 24]
注意
如果
return_exceptions
為 False,則在標記為完成後取消 gather() 不會取消任何已提交的等待項。例如,gather 可以在將異常傳播給調用者後標記為已完成,因此,在從 collect 捕獲異常(由 awaitables 之一引發)後調用gather.cancel()
不會取消任何其他 awaitables。在 3.7 版中更改:如果
gather
本身被取消,取消被傳播而不管return_exceptions
.在 3.10 版中更改:刪除了
loop
範圍。自 3.10 版起已棄用:如果沒有提供位置參數或者不是所有位置參數都是Future-like 對象並且沒有正在運行的事件循環,則會發出棄用警告。
相關用法
- Python asyncio.BaseTransport.get_extra_info用法及代碼示例
- Python asyncio.shield用法及代碼示例
- Python asyncio.run用法及代碼示例
- Python asyncio.wait_for用法及代碼示例
- Python asyncio.create_task用法及代碼示例
- Python asyncio.Task.cancel用法及代碼示例
- Python asyncio.loop.run_in_executor用法及代碼示例
- Python asyncio.Server用法及代碼示例
- Python asyncio.Server.serve_forever用法及代碼示例
- Python asyncio.Event用法及代碼示例
- Python asyncio.sleep用法及代碼示例
- Python asyncio.to_thread用法及代碼示例
- Python asyncio.Condition用法及代碼示例
- Python asyncio.SelectorEventLoop用法及代碼示例
- Python asyncio.run_coroutine_threadsafe用法及代碼示例
- Python asyncio.Lock用法及代碼示例
- Python asyncio.Future.add_done_callback用法及代碼示例
- Python asyncio.loop.shutdown_asyncgens用法及代碼示例
- Python asyncio.as_completed用法及代碼示例
- Python asyncio.Semaphore用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 asyncio.gather。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。