欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python asyncio如何使用

程序员文章站 2024-01-19 09:41:04
node2:/root/python3#cat t17.py import asyncioimport aiohttpimport timeasync def download_one(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: print('Read {} from {}'.format(resp.content....
node2:/root/python3#cat t17.py 
import asyncio
import aiohttp
import time

async def download_one(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            print('Read {} from {}'.format(resp.content_length, url))

async def download_all(sites):
    tasks = [asyncio.create_task(download_one(site)) for site in sites]
    await asyncio.gather(*tasks)

def main():
    sites = [
        'http://192.168.137.3:9000/test111/',
        'http://192.168.137.3:9000/test222/',
        'http://192.168.137.3:9000/test333/',
	'http://192.168.137.3:9000/test444/'
    ]
    start_time = time.perf_counter()
    asyncio.run(download_all(sites))
    end_time = time.perf_counter()
    print('Download {} sites in {} seconds'.format(len(sites), end_time - start_time))
    
if __name__ == '__main__':
    main()
node2:/root/python3#python3 t17.py 
Read 16 from http://192.168.137.3:9000/test111/
Read 16 from http://192.168.137.3:9000/test222/
Read 16 from http://192.168.137.3:9000/test333/
Read 16 from http://192.168.137.3:9000/test444/
Download 4 sites in 8.02225942001678 seconds

本文地址:https://blog.csdn.net/zhaoyangjian724/article/details/108237069

相关标签: python asyncio