how to add a coroutine to a running asyncio loop?

后端 未结 4 1180
慢半拍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 17:13

    You can use create_task for scheduling new coroutines:

    import asyncio
    
    async def cor1():
        ...
    
    async def cor2():
        ...
    
    async def main(loop):
        await asyncio.sleep(0)
        t1 = loop.create_task(cor1())
        await cor2()
        await t1
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))
    loop.close()
    

提交回复
热议问题