簡體   English   中英

Python asyncio-如何懶惰地將as_completed()返回的結果鏈接()?

[英]Python asyncio - How to chain() the results returned from as_completed() lazily?

在以下代碼示例中,我需要為第3步找到解決方案:

import asyncio as aio
import random


async def produce_numbers(x):
    await aio.sleep(random.uniform(0, 3.0))
    return [x * x, x * x + 1, x * x + 2]


async def main():

    # Step 1) Create a list of unawaited coroutines.
    coros = [produce_numbers(i) for i in range(0, 10)]

    # Step 2) Create generator to return items in order of completion.
    futs = aio.as_completed(coros)  # type: generator

    # Step 3) Create a generator that returns every single number lazily.
    # This is the step I don't know how to accomplish.
    # I can't find a way to chain the lists that I get from each
    # `produce_numbers()` call together in a lazy manner.

    # Step 4) This loops should fire as soon as the first
    # `produce_numbers()` coroutine finished.
    for number in my_number_generator:
        print(number)


if __name__ == '__main__':
    loop = aio.get_event_loop()
    loop.run_until_complete(main())

也許我缺少標准庫中的關鍵功能?

asyncio.as_completed()產生期貨,您需要等待每個期貨才能獲得列表結果。 您可以使用帶有雙循環的異步生成器表達式來展平它們:

flattened = (v for fut in futs for v in await fut)

async for number in flattened:
    print(number)

或使用單獨的異步生成器函數對完整語句進行循環:

async def flatten_futures(futures):
    for future in futures:
        for value in await future:
            yield value

並在main()將此用作

async for number in flatten_futures(futs):
    print(number)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM