2017-04-07 79 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))