在循环结束之前从 python 个协程中收集结果
Collecting results from python coroutines before loop finishes
我有一个用 discord.py 构建的 python discord 机器人,这意味着整个程序在事件循环中运行。
我正在处理的功能涉及发出数百个 HTTP 请求并将结果添加到最终列表中。按顺序执行这些操作大约需要两分钟,所以我使用 aiohttp 使它们异步。我的代码的相关部分与 aiohttp 文档中的快速入门示例相同,但它抛出 RuntimeError:Session is closed。该方法取自 https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html 下 'Fetch multiple URLs' 的示例。
async def searchPostList(postUrls, searchString)
futures = []
async with aiohttp.ClientSession() as session:
for url in postUrls:
task = asyncio.ensure_future(searchPost(url,searchString,session))
futures.append(task)
return await asyncio.gather(*futures)
async def searchPost(url,searchString,session)):
async with session.get(url) as response:
page = await response.text()
#Assorted verification and parsing
Return data
我不知道为什么会出现这个错误,因为我的代码与两个可能具有功能的示例非常相似。事件循环本身工作正常。它永远运行,因为这是一个机器人应用程序。
在您链接的示例中,结果收集在 async with
块内。如果您在室外进行,则无法保证在发出请求之前会话不会关闭!
将您的 return 语句移动到块内应该可行:
async with aiohttp.ClientSession() as session:
for url in postUrls:
task = asyncio.ensure_future(searchPost(url,searchString,session))
futures.append(task)
return await asyncio.gather(*futures)
我有一个用 discord.py 构建的 python discord 机器人,这意味着整个程序在事件循环中运行。
我正在处理的功能涉及发出数百个 HTTP 请求并将结果添加到最终列表中。按顺序执行这些操作大约需要两分钟,所以我使用 aiohttp 使它们异步。我的代码的相关部分与 aiohttp 文档中的快速入门示例相同,但它抛出 RuntimeError:Session is closed。该方法取自 https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html 下 'Fetch multiple URLs' 的示例。
async def searchPostList(postUrls, searchString)
futures = []
async with aiohttp.ClientSession() as session:
for url in postUrls:
task = asyncio.ensure_future(searchPost(url,searchString,session))
futures.append(task)
return await asyncio.gather(*futures)
async def searchPost(url,searchString,session)):
async with session.get(url) as response:
page = await response.text()
#Assorted verification and parsing
Return data
我不知道为什么会出现这个错误,因为我的代码与两个可能具有功能的示例非常相似。事件循环本身工作正常。它永远运行,因为这是一个机器人应用程序。
在您链接的示例中,结果收集在 async with
块内。如果您在室外进行,则无法保证在发出请求之前会话不会关闭!
将您的 return 语句移动到块内应该可行:
async with aiohttp.ClientSession() as session:
for url in postUrls:
task = asyncio.ensure_future(searchPost(url,searchString,session))
futures.append(task)
return await asyncio.gather(*futures)