在 python 中等待之前,异步函数中不会调用打印函数

print function does not get called in an async function before await in python

我想获得一些与请求的链接,并且 asyncio.I 有一个示例程序,但我认为存在问题,因为打印函数仅在我使用 await 时被调用。

那么为什么在我调用实际函数的地方没有调用 print 呢?我的理解是,如果使用 await 关键字,函数会中断,直到未来可以呈现。在我的例子中,打印函数应该在 await 关键字之前调用,所以在 print 语句之前调用:doing stuff in between 还是我错了?

import asyncio
import requests
import bs4

urls = ["http://www.google.com", "http://www.google.co.uk"]

async def getContent(url):
    loop = asyncio.get_event_loop()
    print("getting content for: " + url) # print should be called here
    # execute a non async function async
    future = loop.run_in_executor(None, requests.get, url)

    # doing stuff with bs4
    soup = bs4.BeautifulSoup((await future).text, "html.parser") # should now interrupt

    return soup 

async def main():
    loop = asyncio.get_event_loop()

    print("starting gathering...")
    # creating a list of futures
    futures = [getContent(url) for url in urls]
    # packing futures into a awaitable list future
    responses_future = asyncio.gather(*futures)

    print("doing stuff in between...")
    # waiting for all futures
    responses = await responses_future

    print("Done")

    for response in responses:
        print(response)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

输出:

starting gathering...
doing stuff in between...
getting content for: http://www.google.com
getting content for: http://www.google.co.uk
Done

HTML CODE HERE!

此致

协程在等待之前不会执行,这就是它发生的原因