python - 向异步上下文管理器添加超时

标签 python python-asyncio

Python asynchronous context managers很有用,但是它们 do not workasyncio.wait_for Timeouts

向异步上下文管理器添加超时的最佳方法是什么?

最佳答案

What is the best way to add a Timeout to an asynchronous context manager?

您无法将 wait_for 应用于异步上下文管理器,但可以将其应用于使用它的协程。因此,要向上下文管理器添加超时,请在异步函数中使用它,然后对其应用超时。例如:

async def download(url, session):
    async with session.get(url) as resp:
        return await resp.text()

async def print_google(session):
    try:
        text = await asyncio.wait_for(download('http://www.google.com', session), 1)
    except asyncio.TimeoutError:
        text = None
    print(text)

关于python - 向异步上下文管理器添加超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58875597/

相关文章:

python - 将 Pandas 切割操作转换为常规字符串

python - 使用 docker 解压 flask 和 socket-io 脚本时出错

python - 为什么 asyncio 不总是使用执行器?

python - 将 @property 装饰器与 @asyncio.coroutine 一起使用而不可能产生 yield from 吗?

Python aiohttp 请求停止但没有引发异常

python - 将协程传递给 AbstractEventLoop.call_later

python - 构建 Python(3.2) 的 C 扩展但出现错误 "cannot find -lmsvcr90"

python - 使用 Python 执行 GameFbxExporter Maya

python - 如何执行这个列表理解代码?

python - 使用 python 3.6 异步的 UDP 代理服务器