鉴于此功能:
async def read_data(self, stream: UStreams) -> None:
while True:
read_bytes = await stream.read(MAX)
#handle the bytes
当然,这将使函数永远运行。
我想让这个函数执行此操作,但也关闭(因此退出该函数)以防发生事件:
async def read_data(self, stream: UStreams, evt: trio.Event) -> None:
while True:
read_bytes = await stream.read(MAX) || await evt.wait() # <- how do I do this?
#handle the bytes or exit
我不能简单地将
evt.wait()
作为循环中的第一个语句,因为流永远不会被读取(反之亦然也不起作用,因为如果没有东西要处理,事件将永远不会被等待读)。 gather
类型的代码也没有帮助,我不想等待两者:只等待第一个发生(在go
中,这将通过select
语句来解决)。
您可以使用 waiting 原语之一,例如
asyncio.wait
或 asyncio.as_completed
。
import asyncio
async def select(*awaitables):
return await next(asyncio.as_completed(awaitables))
示例:
async def fast():
await asyncio.sleep(0.2)
return 1
async def slow():
await asyncio.sleep(1)
return 2
async def main():
result = select(fast(), slow())
print(result)
asyncio.run(main())
# 1