Python3.4之后推出了asyncio模块 + Python3.5推出async、async语法,内部基于协程,并且遇到IO请求自动化切换import asyncio
async def func1():
print(1)
await asyncio.sleep(2)
print(2)
async def func2():
print(3)
await asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
import aiohttp
import asyncio
async def fetch(seesion, url):
print('发送请求:', url)
async with session.get(url, verify_ssl=False) as response:
content = await response.content.read()
file_name = url.rsplit('_')[-1]
with open(file_name, mode='wb') as file_object:
file_object.write(content)
async def main():
async with aiohttp.ClientSession() as session:
url_list = [
'http://www.autoimg.com/....',
'http://www.autoimg.com/....',
'http://www.autoimg.com/....'
]
tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
await asyncio.wait(tasks)
if __name__ = '__main__':
asyncio.run(main))