Ada*_*kin 14 python python-asyncio
我无法理解asyncio.create_task()Python 3.7 中引入的函数应该如何工作。如果我做:
import asyncio
async def helloworld():
print("Hello world from a coroutine!")
asyncio.create_task(helloworld())
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(helloworld())
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
我得到:
Hello world from a coroutine!
Hello world from a coroutine!
作为输出(即协程运行两次)。这怎么不是无限递归呢?当我使用await关键字时,我希望看到我看到的内容:
import asyncio
async def helloworld():
print("Hello world from a coroutine!")
await helloworld()
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(helloworld())
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
有了这个,我得到:
Hello world from a coroutine!
Hello world from a coroutine!
Hello world from a coroutine!
... many more lines...
Traceback (most recent call last):
File "test3.py", line 53, in <module>
main()
File "test3.py", line 48, in main
loop.run_until_complete(helloworld())
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete
return future.result()
File "test3.py", line 37, in helloworld
await helloworld()
File "test3.py", line 37, in helloworld
await helloworld()
File "test3.py", line 37, in helloworld
await helloworld()
[Previous line repeated 984 more times]
File "test3.py", line 36, in helloworld
print("Hello world from a coroutine!")
RecursionError: maximum recursion depth exceeded while calling a Python object
create_taskonly 是如何调度一次的,以及何时使用它的用例是什么(因为它必须在事件循环已经运行的上下文中运行)?
任务没有安排一次,但循环只运行到 helloworld完成。您会看到消息打印两次,因为循环让下一个任务运行。之后,任务停止运行,因为循环不再运行。
如果你改变
loop.run_until_complete(helloworld())
Run Code Online (Sandbox Code Playgroud)
到
loop.create_task(helloworld())
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)
你会看到Hello world from a coroutine!反复打印出来。
| 归档时间: |
|
| 查看次数: |
6167 次 |
| 最近记录: |