我怎样才能防止一个孩子拆掉整个托儿所引起的异常

2024-04-27 21:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑下面的代码:

import trio


async def broken_fn():
    await trio.sleep(4)
    print(1 / 0)


async def worker_fn():
    while True:
        print("working...")
        await trio.sleep(1)


async def main():
    async with trio.open_nursery() as nursery:
        nursery.start_soon(broken_fn)
        nursery.start_soon(worker_fn)


trio.run(main)

如何防止broken_fn引发的异常在不涉及broken_fn定义的情况下中止其在托儿所中的兄弟姐妹?以下是最好的方法吗

async def main():
    async def supress(fn):
        try:
            await fn()
        except Exception as e:
            print(f"caught {e}!")

    async with trio.open_nursery() as nursery:
        nursery.start_soon(supress, broken_fn)
        nursery.start_soon(worker_fn)

我还有其他选择吗


Tags: asynctriomaindefaswithsleepawait
1条回答
网友
1楼 · 发布于 2024-04-27 21:35:56

如果您正在寻找异常,那么start_soon()中没有忽略异常的机制

您还可以以通用方式执行此操作,以避免为每个单独的函数构建包装器:

from contextlib import suppress
from functools import wraps
from typing import Callable

def suppressed(func: Callable, *exceptions: BaseException):
    @wraps(func)
    async def wrapper(*args, **kwargs):
        with suppress(*exceptions):
            return await func(*args, **kwargs)
        
    return wrapper

然后:

async with trio.open_nursery() as nursery:
    nursery.start_soon(suppressed(broken_fn, Exception))
    nursery.start_soon(worker_fn)

相关问题 更多 >