日常生活的交流与学习

首页 新随笔 联系 管理

async ensuer_future 和 add_done_callback 的用法

import os
from loguru import logger
logger.add(os.path.join(os.path.dirname(__file__) , os.path.basename(__file__).split('.')[0]+'.z.log'))

import time
import asyncio


async def request_img(i):
    logger.debug(f'正在请求第{i}张图片')
    time.sleep(1)
    return f'第{i}张图片' 



def save_img(response):
    logger.debug(response)
    logger.debug(f'保存第{response.result()}图片')


if __name__ == '__main__':
    tasks = []
    for i in range(0,5):
        task = asyncio.ensure_future(request_img(i))
        task.add_done_callback(save_img)
        tasks.append(task)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    logger.debug('所有的图片请求下载完成')



# 2023-07-10 21:52:51.166 | DEBUG    | __main__:request_img:10 - 正在请求第0张图片
# 2023-07-10 21:52:52.167 | DEBUG    | __main__:request_img:10 - 正在请求第1张图片
# 2023-07-10 21:52:53.173 | DEBUG    | __main__:request_img:10 - 正在请求第2张图片
# 2023-07-10 21:52:54.179 | DEBUG    | __main__:request_img:10 - 正在请求第3张图片
# 2023-07-10 21:52:55.185 | DEBUG    | __main__:request_img:10 - 正在请求第4张图片

# 2023-07-10 21:52:56.192 | DEBUG    | __main__:save_img:17 - <Task finished name='Task-1' coro=<request_img() done, defined at /Users/song/Code/script_python/cnblog_upload/src/run.py:9> result='第0张图片'>
# 2023-07-10 21:52:56.193 | DEBUG    | __main__:save_img:18 - 保存第第0张图片图片

# 2023-07-10 21:52:56.194 | DEBUG    | __main__:save_img:17 - <Task finished name='Task-2' coro=<request_img() done, defined at /Users/song/Code/script_python/cnblog_upload/src/run.py:9> result='第1张图片'>
# 2023-07-10 21:52:56.195 | DEBUG    | __main__:save_img:18 - 保存第第1张图片图片

# 2023-07-10 21:52:56.195 | DEBUG    | __main__:save_img:17 - <Task finished name='Task-3' coro=<request_img() done, defined at /Users/song/Code/script_python/cnblog_upload/src/run.py:9> result='第2张图片'>
# 2023-07-10 21:52:56.195 | DEBUG    | __main__:save_img:18 - 保存第第2张图片图片

# 2023-07-10 21:52:56.196 | DEBUG    | __main__:save_img:17 - <Task finished name='Task-4' coro=<request_img() done, defined at /Users/song/Code/script_python/cnblog_upload/src/run.py:9> result='第3张图片'>
# 2023-07-10 21:52:56.196 | DEBUG    | __main__:save_img:18 - 保存第第3张图片图片

# 2023-07-10 21:52:56.196 | DEBUG    | __main__:save_img:17 - <Task finished name='Task-5' coro=<request_img() done, defined at /Users/song/Code/script_python/cnblog_upload/src/run.py:9> result='第4张图片'>
# 2023-07-10 21:52:56.196 | DEBUG    | __main__:save_img:18 - 保存第第4张图片图片

# 2023-07-10 21:52:56.197 | DEBUG    | __main__:<module>:30 - 所有的图片请求下载完成

posted on 2023-07-10 21:57  lazycookie  阅读(28)  评论(0编辑  收藏  举报