首页 > 编程语言 > 详细

python多线程下载器

时间:2017-02-04 18:52:07      阅读:283      评论:0      收藏:0      [点我收藏+]
import requests
import threading

class downloader:
    def __init__(self):
        self.url=http://51reboot.com/src/blogimg/pc.jpg
        self.num=8
        self.name=self.url.split(/)[-1]
        r = requests.head(self.url)
        self.total = int(r.headers[Content-Length])
        print total is %s % (self.total)
    def get_range(self):
        ranges=[]
        offset = int(self.total/self.num)
        for i in  range(self.num):
            if i==self.num-1:
                ranges.append((i*offset,‘‘))
            else:
                ranges.append((i*offset,(i+1)*offset))
        return ranges
    def download(self,start,end):
        headers={Range:Bytes=%s-%s % (start,end),Accept-Encoding:*}
        res = requests.get(self.url,headers=headers)
        self.fd.seek(start)
        self.fd.write(res.content)
    def run(self):
        self.fd =  open(self.name,w)
        thread_list = []
        n = 0
        for ran in self.get_range():
            start,end = ran
            print thread %d start:%s,end:%s%(n,start,end)
            n+=1
            thread = threading.Thread(target=self.download,args=(start,end))
            thread.start()
            thread_list.append(thread)
        for i in thread_list:
            i.join()
        print download %s load success%(self.name)
        self.fd.close()
if __name__==__main__:
    down = downloader()
    down.run()

 

python多线程下载器

原文:http://www.cnblogs.com/vinchx/p/6366031.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!