gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:25:17 25 4
gpt4 key购买 nike

我想获得一些与请求和 asyncio 的链接。我有一个示例程序,但我认为存在问题,因为只有在我使用 await 时才会调用打印函数。

那么为什么在我调用实际函数的地方不调用 print 呢?据我了解,如果使用 await 关键字,该函数会中断,直到 future 出现。在我的例子中,打印函数应该在 await 关键字之前被调用,所以在打印语句之前: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!

问候

最佳答案

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

关于python - 在 python 中等待之前,不会在异步函数中调用打印函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37498791/

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