天天看點

IO并發.1 asyncio執行多個requests請求

#-*- coding:utf-8 -*-
# asyncio是Python 3.4版本引入的标準庫,直接内置了對異步IO的支援。
# asyncio的程式設計模型就是一個消息循環。我們從asyncio子產品中直接擷取一個EventLoop的引用,
# 然後把需要執行的協程扔到EventLoop中執行,就實作了異步IO。

#本例:同時下載下傳多個百度詞典
import asyncio
import dict_down #調用:https://blog.csdn.net/meizhen51/article/details/79861796

#聲明這是并發函數
@asyncio.coroutine
def _get_dict(key):
    content=dict_down.get_dict(key)
    print(content)

#同時下載下傳多個詞典
def get_dict_more(keys=[]):
    if len(keys) == 0:
        return
    loop = asyncio.get_event_loop()
    tasks=[]
    for key in keys:
        tasks.append(_get_dict(key))#添加任務
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

if __name__ == '__main__':
    get_dict_more(keys=['逸周書','國語','戰國策','穆天子傳','竹書紀年','世本'])