我无法理解 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! 重复打印出来。
