什么时候在 Python 中使用 Await Keywork?



我目前正在尝试学习Python中的asyncio。我知道 await 关键字告诉循环它可以切换协程。但是,我应该什么时候实际使用它?为什么不把它放在一切之前呢?

另外,为什么 await 在 'response.text((' 之前,为什么不在 session.get(url( 之前?

async def print_preview(url):
# connect to the server
async with aiohttp.ClientSession() as session:
# create get request
async with session.get(url) as response:
# wait for response
response = await response.text()
# print first 3 not empty lines
count = 0
lines = list(filter(lambda x: len(x) > 0, response.split('n')))
print('-'*80)
for line in lines[:3]:
print(line)
print()

您可以将await与文档中标记为协程的函数一起使用。例如,ClientResponse.text标记为协程,而ClientResponse.close则不是,这意味着您必须等待前者,而不能等待后者。如果你忘记等待协程,它根本不会执行,它的返回值将是一个"协程对象",这是无用的(除了与await一起使用(。

session.get()返回异步上下文管理器。当传递给async with时,它实现的协程在幕后等待。

另请注意,等待并不是您可以使用协程执行的唯一操作,另一个是将它们转换为任务,这允许它们并行运行(无需在操作系统级别产生额外费用(。有关更多信息,请参阅有关 asyncio 的教程。

最新更新