在 python 中等待之前,不会在异步函数中调用 print 函数
Posted
技术标签:
【中文标题】在 python 中等待之前,不会在异步函数中调用 print 函数【英文标题】:print function does not get called in an async function before await in python 【发布时间】:2016-09-26 16:44:02 【问题描述】:我想获得一些请求和异步的链接。我有一个示例程序,但我认为有一个问题,因为打印函数只有在我使用 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!
问候
【问题讨论】:
【参考方案1】:协程在等待之前不会被执行,这就是它发生的原因
【讨论】:
好的,谢谢。我在文档中找到了这句话,它总结了我必须做的事情:Calling a coroutine does not start its code running – the coroutine object returned by the call doesn’t do anything until you schedule its execution. There are two basic ways to start it running: call await coroutine or yield from coroutine from another coroutine (assuming the other coroutine is already running!), or schedule its execution using the ensure_future() function or the BaseEventLoop.create_task() method.
以上是关于在 python 中等待之前,不会在异步函数中调用 print 函数的主要内容,如果未能解决你的问题,请参考以下文章
在映射下一项之前,异步等待映射不等待异步函数在映射函数内部完成