为什么从 main() 调用时 'await' 从本地函数中断?

Why does 'await' break from the local function when called from main()?

我是异步编程的新手,虽然我理解大多数概念,但有一个与 'await' 的内部 运行 相关的概念我不太明白。

考虑以下因素:

import asyncio

async def foo():
    print('start fetching')
    await asyncio.sleep(2)
    print('done fetcihng')

async def main():
    task1 = asyncio.create_task(foo())

asyncio.run(main())

输出:start fetching

对比

async def foo():
    print('start fetching')
    print('done fetcihng')

async def main():
    task1 = asyncio.create_task(foo())

asyncio.run(main())

输出:start fetching 后跟 done fetching

也许这是我对 await 的理解,我确实理解我们可以用它来暂停(在上面的例子中是 2 秒),或者等待函数完全完成 运行ning 然后再继续代码是 运行.

但是对于上面的第一个例子,为什么 await 导致 'done fetching' 而不是 运行?

asyncio.create_task 在事件循环中安排一个可等待对象并立即 returns ,所以你实际上是在任务完成之前退出主函数(并关闭事件循环)

您需要将 main 更改为

async def main():
    task1 = asyncio.create_task(foo())
    await task1

async def main():
    await foo()

先创建任务(前者)在很多情况下都很有用,但它们都涉及事件循环比任务持续时间更长的情况,例如一个长 运行 服务器,否则你应该直接 await 协同程序,就像后者