什么时候应该使用Task而不是coroutine?

Roh*_*tri 11 python task python-asyncio

任何人都可以提供有关如何在python asyncio模块的任务和协同程序之间进行选择的实用建议吗?

如果我要以异步方式实现某些目标,我可以做以下2中的任何一项 -

import asyncio

@asyncio.coroutine
def print_hello():
    print('Hello')

loop = asycio.get_event_loop()
loop.run_until_complete(print_hello)
loop.close()
Run Code Online (Sandbox Code Playgroud)

要么

import asyncio

@asyncio.coroutine
def print_hello():
    print('Hello')

print_task = asyncio.ensure_future(print_hello)

loop = asycio.get_event_loop()
loop.run_until_complete(asyncio.wait_for(print_task))
loop.close()
Run Code Online (Sandbox Code Playgroud)

哪些因素决定了上述两种方法中的哪一种?

Bac*_*ics 1

“通常,当您想要使用yield from将协程直接耦合到调用父协程时,您会使用协程。这种耦合驱动子协程并强制父协程等待子协程返回后再继续。另一方面,不必由父协程驱动,因为它可以自行驱动。” - 松戈洛洛

(请勿回复评论中的内容)