【问题标题】:Await only for some time in Python在 Python 中只等待一段时间
【发布时间】:2017-07-21 17:02:23
【问题描述】:

所以等待服务器会带来痛苦:

    import asyncio 
    #...
    greeting = await websocket.recv() # newer ends

我想要类似的东西

    greeting = await websocket.recv() for seconds(10)

那么如何在 Python 中只等待有限的时间?

【问题讨论】:

  • 查看文档。这个方法是否带超时参数?
  • 我想知道 await sintax,不是特定的方法
  • 什么是websocket?你可以做greeting = yield from asyncio.wait_for(websocket.recv(), timeout=10)

标签: python python-3.x async-await


【解决方案1】:

await expressions 没有超时参数,但 asyncio.wait_for(感谢 AChampion)函数有。我的猜测是,这是因为与语言本身中的协程定义相关联的 await 表达式不依赖于时钟或特定的事件循环。该功能留给标准库的 asyncio 模块。

【讨论】:

  • 与 asyncio 一起使用的默认 await 关键字在某种程度上具有内置超时,我可以看到 TimeoutError: [Errno 110] Connection timed out。代码行File "/usr/lib/python3.6/asyncio/selector_events.py", line 714
  • 这是连接中的网络堆栈(OS)级别错误,而不是等待中止连接。
猜你喜欢
  • 2020-07-16
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 2021-05-08
相关资源
最近更新 更多