@types.coroutine def__sleep0(): """Skip one event loop run cycle. This is a private helper for 'asyncio.sleep()', used when the 'delay' is set to 0. It uses a bare 'yield' expression (which Task.__step knows how to handle) instead of creating a Future object. """ yield
asyncdefsleep(delay, result=None, *, loop=None): """Coroutine that completes after a given time (in seconds).""" if delay <= 0: await __sleep0() return result
if loop isNone: loop = events.get_running_loop() else: warnings.warn("The loop argument is deprecated since Python 3.8, " "and scheduled for removal in Python 3.10.", DeprecationWarning, stacklevel=2)
defget_running_loop(): """Return the running event loop. Raise a RuntimeError if there is none. This function is thread-specific. """ # NOTE: this function is implemented in C (see _asynciomodule.c) loop = _get_running_loop() if loop isNone: raise RuntimeError('no running event loop') return loop
def_get_running_loop(): """Return the running event loop or None. 输出一个event loop,主要是一个循环事件的TLS This is a low-level function intended to be used by event loops. This function is thread-specific. """ # NOTE: this function is implemented in C (see _asynciomodule.c) running_loop, pid = _running_loop.loop_pid if running_loop isnotNoneand pid == os.getpid(): return running_loop
可以看出来一点,get_running_loop(获取事件循环)的主要功能就是返回当前 OS 线程中正在运行的事件循环,这样可能说起来抽象一点,大白话的意思就是事件循环是asyncio的核心,异步任务的运行、任务完成之后的回调、网络IO操作、子进程的运行,都是通过事件循环完成的。所以这个相当于是发动机了。
# Run "set_after()" coroutine in a parallel Task. # 创建一个task,去设置future的结果 # We are using the low-level "loop.create_task()" API here because # 开始 # we already have a reference to the event loop at hand. # Otherwise we could have just used "asyncio.create_task()". loop.create_task( set_after(fut, 1, '... world'))
print('hello ...')
# Wait until *fut* has a result (1 second) and print it. print(await fut)