Python Asyncio - Pythonic way of waiting until condition satisfied

会有一股神秘感。 提交于 2021-01-27 13:27:49

问题


I need to wait until a certain condition/equation becomes True in a asynchronous function in python. Basically it is a flag variable which would be flagged by a coroutine running in asyncio.create_task(). I want to await until it is flagged in the main loop of asyncio. Here's my current code:

import asyncio
flag = False

async def bg_tsk():
    await asyncio.sleep(10)
    flag = True

async def waiter():
    asyncio.create_task(bg_tsk())
    await asyncio.sleep(0)
    # I find the below part unpythonic
    while not flag:
        await asyncio.sleep(0.2)

asyncio.run(waiter())

Is there any better implementation of this? Or is this the best way possible? I have tried using 'asyncio.Event', but it doesnt seem to work with 'asyncio.create_task()'.


回答1:


Using of asyncio.Event is quite straightforward. Sample below.

Note: Event should be created from inside coroutine for correct work.

import asyncio


async def bg_tsk(flag):
    await asyncio.sleep(3)
    flag.set()


async def waiter():
    flag = asyncio.Event()
    asyncio.create_task(bg_tsk(flag))
    await flag.wait()
    print("After waiting")


asyncio.run(waiter())


来源:https://stackoverflow.com/questions/65352682/python-asyncio-pythonic-way-of-waiting-until-condition-satisfied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!