我正在尝试使用 python 中的异步从网站获取数据。作为示例,我使用了此代码(在 A Better Coroutine Example 下):https ://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/
现在这工作正常,但它将二进制块写入文件,我不希望它在文件中。我想要直接得到的数据。但是我目前有一个协程对象列表,我无法从中获取数据。
编码:
# -*- coding: utf-8 -*-
import aiohttp
import asyncio
import async_timeout
async def fetch(session, url):
with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.text()
async def main(loop, urls):
async with aiohttp.ClientSession(loop=loop) as session:
tasks = [fetch(session, url) for url in urls]
await asyncio.gather(*tasks)
return tasks
# time normal way of retrieval
if __name__ == '__main__':
urls = [a list of urls..]
loop = asyncio.get_event_loop()
details_async = loop.run_until_complete(main(loop, urls))
谢谢
问题出return tasks
在 的末尾main()
,原始文章中没有。asyncio.gather
您应该返回由 返回的元组,而不是返回协程对象(一旦传递到 就没有用)asyncio.gather
,它包含以正确顺序运行协程的结果。例如:
async def main(loop, urls):
async with aiohttp.ClientSession(loop=loop) as session:
tasks = [fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks)
return results
现在loop.run_until_complete(main(loop, urls))
将返回与 URL 相同顺序的文本元组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句