gpt4 book ai didi

python - asyncio.create_task 与等待

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:33 28 4
gpt4 key购买 nike

我无法理解 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()

我得到:

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怎么样了?仅被安排一次,您何时可以使用它的用例是什么(因为它必须在事件循环已经运行的上下文中运行)?

最佳答案

任务不会被安排一次,但循环只会运行到 helloworld 完成。您会看到消息打印两次,因为循环让下一个任务运行。之后,任务停止运行,因为循环不再运行。

如果你改变

loop.run_until_complete(helloworld())

loop.create_task(helloworld())
loop.run_forever()

你会看到 Hello world from a coroutine! 重复打印出来。

关于python - asyncio.create_task 与等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51680178/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com