【发布时间】:2018-08-03 21:17:38
【问题描述】:
我无法理解 Python 3.7 中引入的 asyncio.create_task() 函数应该如何工作。如果我这样做:
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()
我明白了:
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()
这样我得到:
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_task 是如何只被调度一次的,什么情况下可以使用它(因为它必须在事件循环已经运行的上下文中运行)?
【问题讨论】:
标签: python python-asyncio