【问题标题】:Why do I need to await twice为什么我需要等待两次
【发布时间】:2022-07-12 21:04:29
【问题描述】:

我正在尝试运行一些 IO 阻塞代码,所以我使用 to_thread 将函数发送到另一个线程。我尝试了几件事,但在所有情况下,我似乎都必须 await to_thread 它只返回 another 协程(?!),然后我必须再次 await。出于某种原因,这不是很点击。

import asyncio

async def search(keyword_list):
    coroutines = set()
    for index, kw in enumerate(keyword_list):
            coroutines.add(asyncio.to_thread(do_lookup, keyword, index))

    for result in asyncio.as_completed(coroutines):
        outcome, index = await result
        # Do some magic with the outcome and index
        # BUT, this doesn't work because `await result` apparently
        # just returns ANOTHER coroutine!


async def do_lookup(keyword, index):
    # Do long, blocking stuff here
    print(f'running...{keyword} {index}')
    return keyword, index


if __name__ == '__main__':
    asyncio.run(search([1, 2, 3, 4]))

【问题讨论】:

    标签: python async-await python-asyncio


    【解决方案1】:

    当我复制/粘贴并调整我的代码以制作一个通用示例时,我在这里发现了问题。

    do_lookup 应该是一个 同步 函数,所以通过定义它 async dev do_lookup 我将它定义为一个 异步 函数,从而导致“双" await 问题。

    只需重新定义 do_lookup 而不使用 async 关键字就可以了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 2019-04-09
      相关资源
      最近更新 更多