如何在不使用`return`语句的情况下打破asyncio协同程序?

时间:2018-01-10 21:53:55

标签: python python-3.x python-3.6 python-asyncio

如果except语句捕获,我在决定如何突破这个协程时遇到了一些麻烦。通常情况下,我会使用:

def f(x):
    try:
        foo_var = next(a_volitile_generator(x))
    except Exception:
        print('it broked')
        return
    yield foo_var

然而!我将产生大量的这些生成器函数,使它们成为协同程序,最后Future将它们与它们联系起来。将它们加载到事件循环中。问题在于:

loop = asyncio.get_event_loop()
queue = asyncio.Queue(maxsize=100)

async def f(x, result_queue, *, loop=loop):
    while _some_condition() is True:
        try:
            foo_var = await a_volitile_async_generator(x)
        except Exception:
            print('it broked')
            # HELP BELOW
            raise StopAsyncIteration # <--ONLY OPTION????????
        await result_queue.put(foo_var)

将任何返回到事件循环asyncio中的禁忌,因为您将打破所有内容......即使该值为None

除此之外,我们还要说我要避免提出StopAsyncIteration ...我试图弄清楚这是不是唯一的方法这样做或者如果我有其他选择:

2 个答案:

答案 0 :(得分:1)

评论中@dirn的mentioned为{{3}},您可以使用简单的raise StopAsyncIteration替换break行:

async def f(x, result_queue, *, loop=loop):
    while _some_condition() is True:
        try:
            foo_var = await a_volitile_async_generator(x)
        except Exception:
            print('it broked')
            break
        await result_queue.put(foo_var)

答案 1 :(得分:0)

JFYI,我猜,你做错了什么。

yield from a_volitile_async_generator(x)

如果a_volitile_async_generator是真正的异步生成器,则无效:您can't use yield from