【问题标题】:Is there a difference between 'await future' and 'await asyncio.wait_for(future, None)'?'await future' 和 'await asyncio.wait_for(future, None)' 之间有区别吗?
【发布时间】:2018-02-22 15:21:21
【问题描述】:

对于 python 3.5 或更高版本,直接将await 应用于未来或任务与使用asyncio.wait_for 包装有什么区别?该文档不清楚何时适合使用wait_for,我想知道它是否是旧的基于生成器的库的遗迹。下面的测试程序似乎没有任何区别,但这并不能证明什么。

import asyncio

async def task_one():
    await asyncio.sleep(0.1)
    return 1

async def task_two():
    await asyncio.sleep(0.1)
    return 2

async def test(loop):
    t1 = loop.create_task(task_one())
    t2 = loop.create_task(task_two())

    print(repr(await t1))
    print(repr(await asyncio.wait_for(t2, None)))

def main():
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(test(loop))
    finally:
        loop.close()

main()

【问题讨论】:

    标签: python python-3.5 python-asyncio


    【解决方案1】:

    wait_for 提供了另外两个功能:

    1. 允许定义超时,
    2. 让你指定循环

    你的例子:

    await f1
    await asyncio.wait_for(f1, None)  # or simply asyncio.wait_for(f1)
    

    除了调用额外包装器 (wait_for) 的开销之外,它们是相同的 (https://github.com/python/cpython/blob/master/Lib/asyncio/tasks.py#L318)。

    awaits 都将无限期地等待结果(或异常)。在这种情况下,简单的await 更合适。

    另一方面,如果您提供超时参数,它将等待有时间限制的结果。如果超过超时时间,它将引发 TimeoutError 并且未来将被取消。

    async def my_func():
        await asyncio.sleep(10)
        return 'OK'
    
    # will wait 10s 
    await my_func()
    
    # will wait only 5 seconds and then will raise TimeoutError
    await asyncio.wait_for(my_func(), 5)
    

    另一件事是循环参数。在大多数情况下你不应该被打扰,用例是有限的:为测试注入不同的循环,运行其他循环......

    这个参数的问题是,所有后续任务/函数也应该有这个循环传递......

    更多信息https://github.com/python/asyncio/issues/362

    【讨论】:

    • 您能想出一个重要的情况,即能够指定循环吗?
    【解决方案2】:

    不幸的是,这里的 python 文档有点不清楚,但如果您查看sources,它就很明显了:

    await相反,协程asyncio.wait_for()只允许等待有限的时间,直到未来/任务完成。如果在这段时间内没有完成,则会引发concurrent.futures.TimeoutError

    这个超时时间可以指定为第二个参数。在您的示例代码中,此timeout 参数为None,这导致完全与直接应用await/yield from 具有相同的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 2021-10-27
      • 1970-01-01
      • 2017-12-30
      • 2014-09-29
      • 2019-04-14
      • 1970-01-01
      相关资源
      最近更新 更多