python 多线程将大文件分开下载后在合并的实例

yipeiwu_com6年前Python基础

废话不多说了,上代码吧:

import threading
import requests
import time
import os


class Mythread(threading.Thread):
  def __init__(self,url,startpos,endpos,f):
    super(Mythread,self).__init__()
    self.url=url
    self.startpos=startpos
    self.endpos=endpos
    self.fd=f
  def download(self):
    print('start thread:%s at %s'%(self.getName(),time.time()))
    headers={'Range':'bytes=%s-%s'%(self.startpos,self.endpos)}
    res=requests.get(self.url,headers=headers)
    self.fd.seek(self.startpos)
    self.fd.write(res.content)
    print('Stop thread:%s at%s'%(self.getName(),time.time()))
    self.fd.close()
  def run(self):
    self.download()
if __name__=="__main__":
  url='http://www.wendangxiazai.com/word/b-cfbdc77931b765ce050814a9-1.doc'
  filename=url.split('/')[-1]
  filesize=int(requests.head(url).headers['Content-Length'])
  print('%s filesize:%s'%(filename,filesize))


  threadnum=3
  threading.BoundedSemaphore(threadnum)#允许线程个数
  step=filesize//threadnum
  mtd_list=[]
  start=0
  end=-1
  
  tempf = open('E:\Python\py\web'+filename,'w')
  tempf.close()
  mtd_list=[]
  with open('E:\Python\py\web'+filename,'rb+')as f:
    #获得文件句柄
    fileno=f.fileno()#返回一个整型的文件描述符,可用于底层操作系统的 I/O 操作
    while end<filesize-1:
      start=end+1
      end=start+step-1
      if end>filesize:
        end=filesize
      print ('Start:%s,end:%s'%(start,end))
      dup=os.dup(fileno)#复制文件句柄
      fd=os.fdopen(dup,'rb+',-1)
      t=Mythread(url,start,end,fd)
      t.start()
      mtd_list.append(t)
    for i in mtd_list:
      i.join()
  f.close()

以上这篇python 多线程将大文件分开下载后在合并的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

一百行python代码将图片转成字符画

一百行python代码将图片转成字符画

本文实例为大家分享了python将图片转成字符画的具体代码,供大家参考,具体内容如下 该代码引用了PIL库的Image,所以必须先安装PIP,再安装PIL,记住,我的64位系统居...

djang常用查询SQL语句的使用代码

djang常用查询SQL语句的使用代码

将django语法和sql对应一下,希望对大家有所帮助 查询单个列的值 story.object.values_list("url", flat=True) SELECT `sto...

pytorch制作自己的LMDB数据操作示例

本文实例讲述了pytorch制作自己的LMDB数据操作。分享给大家供大家参考,具体如下: 前言 记录下pytorch里如何使用lmdb的code,自用 制作部分的Code code就是A...

python 画3维轨迹图并进行比较的实例

python 画3维轨迹图并进行比较的实例

一. 数据的格式 首先我们需要x,y,z三个数据进行画图。从本实验用到的数据集KITTI 00.txt中举例: 1.000000e+00 9.043680e-12 2.326809e...

Python实现字符型图片验证码识别完整过程详解

Python实现字符型图片验证码识别完整过程详解

1摘要 验证码是目前互联网上非常常见也是非常重要的一个事物,充当着很多系统的防火墙功能,但是随时OCR技术的发展,验证码暴露出来的安全问题也越来越严峻。本文介绍了一套字符验证码识别的完整...