我想获得一些请求和asyncio的链接。我有一个示例程序,但我认为有一个问题,因为打印函数只在我使用await时被调用。
那么为什么在我调用实际函数的地方不会调用print?我已经理解如果使用await关键字,函数会中断,直到将来可以显示。在我的情况下,应该在await关键字之前调用print函数,因此在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!
此致
答案 0 :(得分:0)