在笔记1中追踪了 call_soon 这中调用方式是如何运行的,这次看一看 run_until_complete 是怎么工作的.
还是由一个简单的例子开始:
import asyncio
async def hi(loop):
print("Hello World")
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(hi(loop))
loop.stop()
loop.close()
一开始还是通过 asyncio.get_event_loop() 得到事件循环, 之后调用了 run_until_complete ,而调用的参数是一个 async 修饰过的函数的返回值,
async def hi():
print("Hello World")
a = hi()
print(type(a))
#Out[3]: coroutine
可以通过简单的调用 type 来得到它的返回类型, 至于到底是什么, 可参见 asyncio.coroutine , 如果非要追究到底,其实在cpython的源码中是有写的,
typedef struct {
/* The gi_ prefix is intended to remind of generator-iterator. */
_PyGenObject_HEAD(gi)
} PyGenObject;
typedef struct {
_PyGenObject_HEAD(cr)
} PyCoroObject;
可以看出 coroutine 和 生成器 其实是一个根源.因此通过 dir() 得到的结果也是很相似的.
回到 run_until_complete