python 多线程利器-tomorrow

前言:

tomorrow 模块,该模块属于第三方的一个模块,使用起来非常的方便,只需要用其中的 threads 方法作为装饰器去修饰一个普通的函数,既可以达到并发的效果,本篇将用实例来展示 tomorrow 的强大之处。后面将对 tomorrow 的实现原理做进一步的分析。

 

一 . 安装

直接用命令:pip install tomorrow

二. 单线程

# coding:utf-8
from bs4 import BeautifulSoup
import requests
import time
import os

# 当前脚本所在目录
cur_path = os.path.dirname(os.path.realpath(__file__))

def get_image():
    r = requests.get('http://699pic.com/sousuo-218808-13-1.html')
    f = r.content
    soup = BeautifulSoup(f,'html.parser')
    # 找出所有标签
    image = soup.find_all(class_='lazy')
    return image

def save_image(image_url):
    try:
        jpg_url = image_url['data-original']
        title = image_url['title']
        '''
        # 判断是否有jpg文件夹,没有就创建一个
        save_file = os.path.join(cur_path,'jpg_haha')
        if not os.path.exists(save_file):
            os.mkdir(save_file)
        '''
        with open(r'F:\pic3\\'+title+'.jpg','wb') as fa:
            fa.write(requests.get(jpg_url).content)
    except Exception as e:
        pass

if __name__=='__main__':
    t1 = time.time()
    image_urls = get_image()
    for i in image_urls:
        save_image(i)
    t2 = time.time()
    print('总耗时:%.2f 秒' % (t2-t1))  # 取小数点后2位

运行结果是:

总耗时:6.16 秒

三. 使用多线程tomorrow

一行代码搞定多线程,在函数前加个@threads(5),括号里面代码线程的数量,数字越大,运行的速度越快;但是数字也不是越大越好,一般在5-10之间。

 代码;

# coding:utf-8
from bs4 import BeautifulSoup
import requests
import time
import os
# 导入tomorrow
from tomorrow import threads

# 当前脚本所在目录
cur_path = os.path.dirname(os.path.realpath(__file__))

def get_image():
    r = requests.get('http://699pic.com/sousuo-218808-13-1.html')
    f = r.content
    soup = BeautifulSoup(f,'html.parser')
    # 找出所有标签
    image = soup.find_all(class_='lazy')
    return image

# 用法简单,只要在需要执行多线程的函数前加上此装饰器即可
@threads(5)
def save_image(image_url):
    try:
        jpg_url = image_url['data-original']
        title = image_url['title']
        '''
        # 判断是否有jpg文件夹,没有就创建一个
        save_file = os.path.join(cur_path,'jpg_haha')
        if not os.path.exists(save_file):
            os.mkdir(save_file)
        '''
        with open(r'F:\pic3\\'+title+'.jpg','wb') as fa:
            fa.write(requests.get(jpg_url).content)
    except Exception as e:
        pass

if __name__=='__main__':
    t1 = time.time()
    image_urls = get_image()
    for i in image_urls:
        save_image(i)
    t2 = time.time()
    print('总耗时:%.2f 秒' % (t2-t1))  # 取小数点后2位

运行结果如下:

总耗时:0.41 秒

 由此总结,速度真是快上不少倍哈!

有机会待续...

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不过如此1951

如果有收获,可以打赏一下

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值