如何在不使用 `return` 语句的情况下跳出 asyncio 协程? [英] How to break out of a asyncio coroutine without using the `return` statement?
问题描述
如果 except
语句被捕获,我在决定如何跳出这个协程时会遇到一些麻烦.通常,我只会使用:
I'm having a bit of trouble deciding how to break out of this coroutine if the except
statement catches. Normally, I would just use:
def f(x):
try:
foo_var = next(a_volitile_generator(x))
except Exception:
print('it broked')
return
yield foo_var
但是!我将产生无数的这些生成器函数,使它们成为协程,最后 Future
将它们和化将它们加载到事件循环中.问题来了:
However! I'm going to spawn a gazillion of these generator funcs, make them coroutines, and finally Future
ize them & load them into an event-loop. Here's the issue:
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代码>.
returning anything into the event-loop is a no-no in asyncio
because you'll break everything...even if that value is None
.
除此之外,我们还要说我想避免提高 StopAsyncIteration
......我试图弄清楚这是唯一的方法还是我有其他选择:
Aside from that, let's also say I'd like to avoid raising StopAsyncIteration
...I'm trying to figure out if that's the only way to do this or if I have other options:
推荐答案
As 由@dirn 在评论中提到,您可以用简单的 break<替换
raise StopAsyncIteration
行/代码>:
As mentioned by @dirn in the comments, you can replace your raise StopAsyncIteration
line with a simple 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)
这篇关于如何在不使用 `return` 语句的情况下跳出 asyncio 协程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!