当前位置: 首页 > 工具软件 > asyncio > 使用案例 >

asyncio的基本使用

蔺宇
2023-12-01

asyncio是python用于解决异步io编程的一整套解决方案
也是采用事件循环+回调(驱动生成器)+epoll(IO多路复用)
简单的使用asyncio的例子

import asyncio
import time

async def get_html(url):
    print('start get url')
    await asyncio.sleep(1)
    print('end get url')
    
if __name__ == '__main__':
    start = time.time()
    loop = asyncio.get_event_loop()
    tasks = [loop.create_task(get_html('http://www.baidu.com')) for i in range(1000)]
    loop.run_until_complete(asyncio.wait(tasks))
    print(time.time() - start)

这个是最简单的asyncio的使用1000次并发

import asyncio
import time

async def get_html(url):
    print('start get url')
    await asyncio.sleep(1)
    print('end get url')
    return 'haha'
    
if __name__ == '__main__':
    start = time.time()
    loop = asyncio.get_event_loop()
    tasks = loop.create_task(get_html('http://www.baidu.com'))
    loop.run_until_complete(tasks)
    print(tasks.result())
    print(time.time() - start)

获取返回值

import asyncio
import time

async def get_html(url):
    print('start get url')
    await asyncio.sleep(1)
    print('end get url')
    return 'haha'
    
if __name__ == '__main__':
    start = time.time()
    loop = asyncio.get_event_loop()
    tasks = [loop.create_task(get_html('http://www.baidu.com')) for i in rang(100)]
    loop.run_until_complete(asyncio.wait(tasks))
    [print(i.result()) for i in tasks]
    print(time.time() - start)

获取列表返回值

import asyncio
import time
from functools import partial  #


async def get_html(url):
    print('start get url')
    await asyncio.sleep(1)
    print('end get url')
    return 'hehe'


def callback(url, future):
    print(url)
    print('send email to he')


if __name__ == '__main__':
    start = time.time()
    loop = asyncio.get_event_loop()
    tasks = loop.create_task(get_html('http://www.baidu.com'))  # 获取函数返回值
    tasks.add_done_callback(partial(callback, 'kakaka'))  # 当循环执行完成后自信callback函数
    loop.run_until_complete(tasks)
    print(time.time() - start)

当事件循环执行完毕时可调用add_done_callback函数执行,partial函数可将函数和参数封装为一个新的不带参数的函数,用以解决add_done_callback函数只接受函数名的问题

 类似资料: