how to add a coroutine to a running asyncio loop?

后端 未结 4 1187
慢半拍i
慢半拍i 2020-12-23 16:20

How can one add a new coroutine to a running asyncio loop? Ie. one that is already executing a set of coroutines.

I guess as a workaround one could wait for existing

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-23 16:59

    None of the answers here seem to exactly answer the question. It is possible to add tasks to a running event loop by having a "parent" task do it for you. I'm not sure what the most pythonic way to make sure that parent doesn't end until it's children have all finished (assuming that's the behavior you want), but this does work.

    import asyncio
    import random
    
    
    async def add_event(n):
        print('starting ' + str(n))
        await asyncio.sleep(n)
        print('ending ' + str(n))
        return n
    
    
    async def main(loop):
    
        added_tasks = []
    
        delays = [x for x in range(5)]
    
        # shuffle to simulate unknown run times
        random.shuffle(delays)
    
        for n in delays:
            print('adding ' + str(n))
            task = loop.create_task(add_event(n))
            added_tasks.append(task)
            await asyncio.sleep(0)
    
        print('done adding tasks')
    
        results = await asyncio.gather(*added_tasks)
        print('done running tasks')
    
        return results
    
    
    loop = asyncio.get_event_loop()
    results = loop.run_until_complete(main(loop))
    print(results)
    

提交回复
热议问题