gpt4 book ai didi

python - 如果协程使用 asyncio 引发异常,如何关闭循环并打印错误?

转载 作者:太空狗 更新时间:2023-10-29 18:02:04 28 4
gpt4 key购买 nike

假设我有几个协程在循环中运行。如果其中一些程序因异常而失败,那么如何使整个程序因该异常而失败?因为现在 asyncio 甚至不打印协程的错误消息,除非我使用日志记录级别“DEBUG”。

from asyncio import get_event_loop, sleep


async def c(sleep_time=2, fail=False):
print('c', sleep_time, fail)
if fail:
raise Exception('fail')
while True:
print('doing stuff')
await sleep(sleep_time)



loop = get_event_loop()
loop.create_task(c(sleep_time=10, fail=False))
loop.create_task(c(fail=True))
loop.run_forever()

最佳答案

一种优雅的方式是使用错误处理 api。

https://docs.python.org/3/library/asyncio-eventloop.html#error-handling-api

例子:

import asyncio


async def run_division(a, b):
await asyncio.sleep(2)
return a / b


def custom_exception_handler(loop, context):
# first, handle with default handler
loop.default_exception_handler(context)

exception = context.get('exception')
if isinstance(exception, ZeroDivisionError):
print(context)
loop.stop()

loop = asyncio.get_event_loop()

# Set custom handler
loop.set_exception_handler(custom_exception_handler)
loop.create_task(run_division(1, 0))
loop.run_forever()

关于python - 如果协程使用 asyncio 引发异常,如何关闭循环并打印错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43207927/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com