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

时间:2015-08-09 13:50:20

标签: python task python-asyncio

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

如果我要异步实现某事,我可以做以下两种情况之一 -

import asyncio

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

loop = asycio.get_event_loop()
loop.run_until_complete(print_hello)
loop.close()

OR

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()

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

1 个答案:

答案 0 :(得分:1)

"Generally you would use a coroutine when you want to directly couple it to the calling parent coroutine using yield from. This coupling is what drives the child coroutine and forces the parent coroutine to wait for the child coroutine to return prior to continuing. A Task, on the other hand, doesn't have to be driven by a parent coroutine because it can drive itself." - shongololo (Please don't answer things in the comments)