python asyncio

import asyncio
from functools import partial
async def get_url():
    return "aaaa"

async def get_html(url):
    print("start get html %s"%url)
    await asyncio.sleep(2)
    print("end get url %s"%url)
    return "ddddwww"
def done_fun(url,future):
    print(url)

if __name__=="__main__":
    loop=asyncio.get_event_loop()
    #futures=asyncio.ensure_future(get_html("aaaa"))
    #futures=loop.create_task(get_html("aaaa"))##与上句代码一样
    #futures.add_done_callback(partial(done_fun,"http://www.sina.com"))##http://www.sina.com
    #loop.run_until_complete(futures)
    #print(futures.result())##ddddwww
    ##asyncio.wait
    # tasks=[get_html(a) for a in range(4)]
    # loop.run_until_complete(asyncio.wait(tasks))
    ##asyncio.gather
    group1=[get_html(a) for a in range(2)]
    group2 = [get_html(a) for a in range(2,4)]
    group1=asyncio.gather(*group1)
    group2 = asyncio.gather(*group2)
    #group2.cancel()
    loop.run_until_complete(asyncio.gather(group1,group2))

 

posted @ 2019-12-03 18:43  howhy  阅读(71)  评论(0)    收藏  举报