python并发模块之concurrent.futures(二)

上次我们简单的了解下,模块的一些基本方法和用法,这里我们进一步对concurrent.futures做一个了解和拓展.
上次的内容点这。
python并发模块之concurrent.futures(二)
以下载图片为例子,下面的程序是顺序下载http://www.58pic.com/newpic/28660111.html网站的24个表情 。

from requests_html import HTMLSession
import os
import time
BASE_PATH="downloads"
class Get_Image():
    def __init__(self):
        self.timeout=20
        self.session=HTMLSession()
    def getiamge(self,url):
        req=self.session.get(url,timeout=self.timeout)
        if req.status_code==200:
            imgurllist=req.html.xpath("//ul[@class='emoticon-model']/li/img/@data-big")
            for index,url in enumerate(imgurllist):
                print(f"开始下载第{index+1}张图片")
                self.save_image(url,index+1)
        else:
            print("下载失败")
    def save_image(self,imgurl,index):
        print(f"当前下载链接:{imgurl}")
        buff=self.session.get(imgurl,timeout=self.timeout).content
        file_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),BASE_PATH)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        with open(os.path.join(file_path,f"{index}.png"),"wb") as fs:
            fs.write(buff)
if __name__ == '__main__':
    start_url="http://www.58pic.com/newpic/28660111.html"
    start=time.time()
    Get_Image().getiamge(start_url)
    end=time.time()
    print(f"顺序下载24张图片用时:{end-start}")
#运行了两次结果分别为
#顺序下载24张图片用时:14.926000356674194
#顺序下载24张图片用时:14.07800030708313

使用concurrent.futures修改成并发之后

from requests_html import HTMLSession
import os
import time
from concurrent.futures import ThreadPoolExecutor
BASE_PATH="downloads"
MAX_WORKERS = 10 #最多使用10个线程
class Get_Image():
    def __init__(self):
        self.timeout=20
        self.session=HTMLSession()
    def getiamge(self,url):
        req=self.session.get(url,timeout=self.timeout)
        if req.status_code==200:
            imgurllist=req.html.xpath("//ul[@class='emoticon-model']/li/img/@data-big")
            works=min(len(imgurllist),MAX_WORKERS)
            with ThreadPoolExecutor(works) as excutor:
                res=excutor.map(self.save_image,imgurllist,range(1,25))
            return len(list(res))
        else:
            print("下载失败")
    def save_image(self,imgurl,index):
        print(f"当前下载链接:{imgurl}")
        buff=self.session.get(imgurl,timeout=self.timeout).content
        file_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),BASE_PATH)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        with open(os.path.join(file_path,f"{index}.png"),"wb") as fs:
            fs.write(buff)
if __name__ == '__main__':
    start_url="http://www.58pic.com/newpic/28660111.html"
    start=time.time()
    Get_Image().getiamge(start_url)
    end=time.time()
    print(f"并发下载24张图片用时:{end-start}")
#运行了两次结果分别为
#并发下载24张图片用时:7.737000226974487
#并发下载24张图片用时:7.083999872207642

通过观察发现速度并发之后效率大大提高了。

python并发模块之concurrent.futures(二)的更多相关文章

  1. python并发模块之concurrent.futures(一)

    Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threadin ...

  2. python3 线程池-threadpool模块与concurrent.futures模块

    多种方法实现 python 线程池 一. 既然多线程可以缩短程序运行时间,那么,是不是线程数量越多越好呢? 显然,并不是,每一个线程的从生成到消亡也是需要时间和资源的,太多的线程会占用过多的系统资源( ...

  3. python并发编程之multiprocessing进程(二)

    python的multiprocessing模块是用来创建多进程的,下面对multiprocessing总结一下使用记录. 系列文章 python并发编程之threading线程(一) python并 ...

  4. Python3【模块】concurrent.futures模块,线程池进程池

    Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要 ...

  5. python基础-------模块与包(二)

    sys模块.logging模块.序列化 一.sys模块 sys.argv           命令行参数List,第一个元素是程序本身路径 sys.exit(n)        退出程序,正常退出时e ...

  6. Python命令模块argparse学习笔记(二)

    argparse模块可以设置两种命令参数,一个是位置参数,一个是命令参数 位置参数 import argparse parser = argparse.ArgumentParser(descripti ...

  7. Python日志模块的管理(二)

    日志模块可以通过封装一个类,也可以通过配置文件取管理 新建1个log.ini文件 [loggers] keys=root [handlers] keys=fileHandler,streamHandl ...

  8. Python学习-4.Python的模块加载(二)

    1.部分函数加载 from SameFolder import printSameFolder printSameFolder() 该代码指从SameFolder.py中加载printSameFold ...

  9. Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures

    参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...

随机推荐

  1. Go语言【第十三篇】:Go语言递归函数

    Go语言递归函数 递归,就是在运行的过程中调用自己,语法格式如下: func recursion() { recursion() /* 函数调用自身 */ } func main() { recurs ...

  2. Go语言【第七篇】:Go函数

    Go语言函数 函数是基本的代码块,用于执行某个任务.Go语言最少有个main()函数,可以通过函数来划分不同功能,逻辑上每个函数执行的是指定的任务.函数声明告诉了编译器函数的名称,返回类型和参数.Go ...

  3. 《转》HTTP 协议入门

    HTTP 协议是互联网的基础协议,也是网页开发的必备知识,最新版本 HTTP/2 更是让它成为技术热点. 本文介绍 HTTP 协议的历史演变和设计思路. 一.HTTP/0.9 HTTP 是基于 TCP ...

  4. Django错误 OperationalError: no such column: xxx

    模型前后操作如下: 第一次迁移: class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) titl ...

  5. IO模式

    二 IO模式 刚才说了,对于一次IO访问(以read举例),数据会先被拷贝到操作系统内核的缓冲区中,然后才会从操作系统内核的缓冲区拷贝到应用程序的地址空间.所以说,当一个read操作发生时,它会经历两 ...

  6. [LNOI] 相逢是问候 || 扩展欧拉函数+线段树

    原题为2017六省联考的D1T3 给出一个序列,m次操作,模数p和参数c 操作分为两种: 1.将[l,r]区间内的每个数x变为\(c^x\) 2.求[l,r]区间内数的和%p 首先,我们要了解一些数论 ...

  7. HDOJ(HDU).1058 Humble Numbers (DP)

    HDOJ(HDU).1058 Humble Numbers (DP) 点我挑战题目 题意分析 水 代码总览 /* Title:HDOJ.1058 Author:pengwill Date:2017-2 ...

  8. Spring面试,IoC和AOP的理解(转)

    spring 的优点?1.降低了组件之间的耦合性 ,实现了软件各层之间的解耦 2.可以使用容易提供的众多服务,如事务管理,消息服务等 3.容器提供单例模式支持 4.容器提供了AOP技术,利用它很容易实 ...

  9. spring 整合 redis 单机版

    增加spring配置文件: application-jedis.xml <?xml version="1.0" encoding="UTF-8"?> ...

  10. HBase客户端访问超时的多个因素及参数

    在一个需要低延时响应的hbase集群中,使用hbase默认的客户端超时配置简直就是灾难. 但是我们可以考虑在客户端上加上如下几个参数,去改变这种状况: 1. hbase.rpc.timeout: RP ...