Python asynchronous context managers很有用,但是它们 do not work与 asyncio.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/