极速方程式第二部,新沂政府网,环保概念
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)) #text_len = await resp.text() #print('read {} from {}'.format(len(text_len), url)) #print('len(text_len)',len(text_len)) async def download_all(sites): tasks = [asyncio.create_task(download_one(site)) for site in sites] await asyncio.gather(*tasks) def main(): sites = [ 'https://www.baidu.com/', 'https://pypi.org/', 'https://www.sina.com.cn/', 'https://www.163.com/', 'https://news.qq.com/', 'http://www.ifeng.com/', 'http://www.ce.cn/', 'https://news.baidu.com/', 'http://www.people.com.cn/', 'http://www.ce.cn/', 'https://news.163.com/', 'http://news.sohu.com/' ] 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() # 输出 read 227 from https://www.baidu.com/ read none from http://www.ce.cn/ read none from http://www.ce.cn/ read 38914 from http://www.people.com.cn/ read none from https://news.qq.com/ read none from https://news.163.com/ read none from https://www.163.com/ read 129268 from https://www.sina.com.cn/ read none from http://www.ifeng.com/ read none from https://news.baidu.com/ read none from http://news.sohu.com/ read 4293 from https://pypi.org/ download 12 sites in 0.7875643999999999 seconds
loop = asyncio.get_event_loop() try: loop.run_until_complete(coro) finally: loop.close()
可以遵循以下伪代码的规范:
if io_bound: if io_slow: print('use asyncio') else: print('use multi-threading') else if cpu_bound: print('use multi-processing')
极客时间《python核心技术与实战》专栏
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
python求numpy中array按列非零元素的平均值案例
网友评论