• python asyncio 测试


    实例二:

    import aiohttp
    import asyncio
    
    async def fetch(session, url):
        print("发送请求:", url)
        async with session.get(url, verify_ssl=False) as response:
            content = await response.content.read()
            file_name = url.rsplit('_')[-1]
            with open(file_name, mode='wb') as file_object:
                file_object.write(content)
    
    
    async def main():
        async with aiohttp.ClientSession() as session:
            url_list = [
                'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
                'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg',
                'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg'
            ]
            tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
            await asyncio.wait(tasks)
    
    if __name__ == '__main__':
        # asyncio.run(main())
        loop = asyncio.get_event_loop() #可以防止报错
        loop.run_until_complete(main())
    
    

    实例二:

    import asyncio
    async def func():
        print(1)
        await asyncio.sleep(2)
        print(2)
        return "返回值"
    async def main():
        print("main开始")
        # 创建协程,将协程封装到Task对象中并添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态)。
        # 再调用
        task_list = [
            asyncio.create_task(func(), name="n1"),    # 带参数name要做python3.9.0才行,python3.7.2对于参数name报错
            asyncio.create_task(func(), name="n2")
        ]
        print("main结束")
        # 当执行某协程遇到IO操作时,会自动化切换执行其他任务。
        # 此处的await是等待所有协程执行完毕,并将所有协程的返回值保存到done
        # 如果设置了timeout值,则意味着此处最多等待的秒,完成的协程返回值写入到done中,未完成则写到pending中。
        done, pending = await asyncio.wait(task_list, timeout=None)  # done是任务完成返回值的集合,pending是未完成的任务
        print(done, '\n',pending)
    asyncio.run(main())
    
  • 相关阅读:
    [leetcode]Palindrome Partitioning II
    [wikioi]传纸条
    [leetcode]Palindrome Partitioning
    [leetcode]Convert Sorted List to Binary Search Tree
    [topcoder]ActivateGame
    [topcoder]NinePuzzle
    [topcoder]BestRoads
    [topcoder]IncreasingSubsequences
    [leetcode]Surrounded Regions
    CF 432B :Football Kit
  • 原文地址:https://www.cnblogs.com/heris/p/16306833.html
Copyright © 2020-2023  润新知