python:等待从套接字读取或在事件发生时关闭

问题描述 投票:0回答:1

鉴于此功能:

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
语句来解决)。

python asynchronous async-await python-trio
1个回答
0
投票

您可以使用 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
© www.soinside.com 2019 - 2024. All rights reserved.