Asyncio:保留多个协程 运行
Asyncio: keep multiple coroutines running
我有多个协程需要同时 运行(永远)。对于错误处理,其中一个例程偶尔会结束并需要重新生成,我使用以下代码,但它假定需要重新启动的是 coroutine1。
pending = {coroutine1(), coroutine2()}
while True:
a = asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
done, pending = loop.run_until_complete(a)
pending = pending | {coroutine1()}
我怎样才能以更好、更通用的方式解决这个问题?
使用不同的方法怎么样?
async def run_forever(corofn):
while True:
await corofn()
corofns = coroutine1, coroutine2
await asyncio.wait(map(run_forever, corofns))
我有多个协程需要同时 运行(永远)。对于错误处理,其中一个例程偶尔会结束并需要重新生成,我使用以下代码,但它假定需要重新启动的是 coroutine1。
pending = {coroutine1(), coroutine2()}
while True:
a = asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
done, pending = loop.run_until_complete(a)
pending = pending | {coroutine1()}
我怎样才能以更好、更通用的方式解决这个问题?
使用不同的方法怎么样?
async def run_forever(corofn):
while True:
await corofn()
corofns = coroutine1, coroutine2
await asyncio.wait(map(run_forever, corofns))