如何在python中实现asyncio.sleep()? [英] how is asyncio.sleep() in python implemented?
问题描述
我是python3的新手爱好者,他希望了解该库如何实现asyncio.sleep().
I'm a newbie python3 enthusiast, who hopes to find out how asyncio.sleep() is implemented by the library.
我有能力编写协程,但似乎无法考虑如何开始为异步睡眠编写代码.
I'm capable of writing coroutines but I can't seem to think about how to start writing code for asynchronous sleep.
如果您直接共享代码或提供有关如何在本地计算机上查找代码的快速教程,那将很棒.谢谢!
would be great if you share the code directly or give a quick tutorial on how to find the code on my local machine. thank you!
推荐答案
对于使用Python实现的代码(与C扩展相对),如果您使用的是 ipython
,那么一种简单的方法可以查看源代码是使用 ??
运算符.例如,在我的3.6安装中:
For code implemented in Python (as opposed to C extensions), if you're using ipython
, an easy way to see the source code is to use the ??
operator. For example, on my 3.6 install:
In [1]: import asyncio
In [2]: asyncio.sleep??
Signature: asyncio.sleep(delay, result=None, *, loop=None)
Source:
@coroutine
def sleep(delay, result=None, *, loop=None):
"""Coroutine that completes after a given time (in seconds)."""
if delay == 0:
yield
return result
if loop is None:
loop = events.get_event_loop()
future = loop.create_future()
h = future._loop.call_later(delay,
futures._set_result_unless_cancelled,
future, result)
try:
return (yield from future)
finally:
h.cancel()
File: c:\program files\python36\lib\asyncio\tasks.py
Type: function
您也可以查看CPython GitHub存储库,但具体取决于在代码组织上,在哪里看可能并不明显(例如,在这种情况下,代码实际上存在于 asyncio.tasks
中,并自动导入到 asyncio
中),而 ipython
魔术师直接为您找到它.
You can also just look at the CPython GitHub repo, but depending on the code organization it may not be obvious where to look (e.g. in this case the code actually exists in asyncio.tasks
, and is auto-imported into asyncio
), while ipython
magic finds it for you directly.
这篇关于如何在python中实现asyncio.sleep()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!