【发布时间】: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