2017-04-07 80 views
1

我有多个协程,需要同时运行(永远)。对于错误处理,其中一个例程偶尔会结束并需要重新生成,然后使用以下代码,但假定它是coroutine1需要重新启动。Asyncio:保持多个协程运行

pending = {coroutine1(), coroutine2()} 
while True: 
    a = asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) 
    done, pending = loop.run_until_complete(a) 
    pending = pending | {coroutine1()} 

如何以更好更一般的方式解决此问题?

回答

0

有关使用了不同的方法是什么?

async def run_forever(corofn): 
    while True: 
     await corofn() 

corofns = coroutine1, coroutine2 
await asyncio.wait(map(run_forever, corofns))