<p>区别在于你是否有收益率声明。
代码如下:</p>
<pre><code>from types import coroutine as t_coroutine
from asyncio import coroutine as a_coroutine, ensure_future, sleep, get_event_loop
@a_coroutine
def a_sleep():
print("doing something in async")
yield 1
@t_coroutine
def t_sleep():
print("doing something in types")
yield 1
async def start():
sleep_a = a_sleep()
sleep_t = t_sleep()
print("Going down!")
loop = get_event_loop()
loop.run_until_complete(start())
</code></pre>
<p>在这个例子中,一切看起来都是一样的——这是来自pycharm的调试信息(我们站在“Going down!”线路)。控制台中尚未打印任何内容,因此函数尚未启动。在</p>
<p><a href="https://i.stack.imgur.com/eIqZb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eIqZb.png" alt="PyCharm Debug"/></a></p>
<p>但是<strong>如果我们删除<code>yield</code></strong>,那么<code>types</code>版本将立即开始工作!在</p>
^{pr2}$
<p>现在我们在控制台中打印了<code>doing something in types</code>。下面是调试信息:</p>
<p><a href="https://i.stack.imgur.com/DF4tM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DF4tM.png" alt="new debug info"/></a></p>
<p>正如您所看到的<strong>如果没有结果并且返回None,它将在调用之后立即开始。在</p>
<hr/>
<p>至于用法,您应该始终使用<code>asyncio</code>版本。如果您需要像<em>fire and forget</em>一样运行它(立即运行,稍后获得结果)-请使用<code>ensure_future</code>函数。在</p>