首页 > 解决方案 > asyncio:异常时停止协程

问题描述

我正在编写一个必须在捕获异常时自行重启的函数,但我不知道该怎么做。我有这段代码,但它不起作用。:

import asyncio

async def main():
    while True:
        try:
            #REALLY huge amount of code
        except Exception as e:
            print(f"Exception: {e}")
            # Here I want this script to run main() again
            return


asyncio.run(main())

标签: pythonasynchronousasync-awaitpython-asyncio

解决方案


你的main函数是一个协程,协程保持状态。重新启动同一个可能不是一个好主意。您需要两个函数, co-routinemain和一个常规函数 main 来处理创建一个新的 co-routine 并再次运行它。

async def amain():
    # Lot of code

def main():
    while True:
        try:
            asyncio.run(amain())
        except KeyboardInterrupt:
            break
        except Exception as e:
            log(e)

类似的东西。


推荐阅读