Python implementation Download interface (with progress bar, breakpoint resume, multi-threaded multi-task download, etc.)

Source: Internet
Author: User

Development environment:

Windows 7 64-bit, Python 3.6.2

Implementation features:

progress bar, download speed and download progress display, breakpoint continuation (pause resume download function), cancel the download and other functions
Download interface,

Click on ' New Task ' to pop up the window to enter the download link.

Click ' Start download ' to automatically get the download file name and select a storage path:

Key code:

Because the breakpoint continues to be appended in the previous file, so open (filename, ' ab ')
The mode to open the file here is AB
The code to implement the breakpoint continuation is as follows:

headers={‘Range‘: ‘bytes=%d-‘ %os.path.getsize(filename) }r = requests.get(self.url,stream=True,headers=headers)with open(filename, ‘ab‘) as code:    for chunk in r.iter_content(chunk_size=1024): #边下载边存硬盘        if chunk :            code.write(chunk)

The code that displays the progress bar (the download progress is displayed by changing the value of the Self.value, which is a range of 0-100):

from tkinter import ttkself.value=IntVar()pb=ttk.Progressbar(self.fm4,length=200,variable=self.value)pb.grid(row=0,column=1)

Attach the key code for the downloaded file:

Import osimport requestsimport timeimport reimport urllibclass Getfile (): #下载文件 def __init__ (self,url): Self.ur        L=url self.flag=true #当self. Flag=false, pause or cancel the download, that is, end the download thread Self.header_flag=false #当为True时, set the header, resume the breakpoint            Self.re=requests.head (url,allow_redirects=true,timeout=20) #运行head方法时重定向 def getsize (self): try:            Self.file_total=int (self.re.headers[' content-length ')) #获取下载文件大小 return self.file_total except: return 0 def getfilename (self): #获取默认下载文件名 if ' content-disposition ' in Self.re.headers:n=sel        F.re.headers.get (' Content-disposition '). Split (' name= ') [1] filename=urllib.parse.unquote (n,encoding= ' UTF8 ') Else:filename=os.path.basename (Self.re.url.split ('? ') [0]) if filename== ': Filename= ' index.html ' return filename def downfile (self,filename): #下载文 Piece self.headers={} self.mode= ' WB ' If Os.path.exists (filenAME) and self.header_flag:self.headers={' Range ': ' bytes=%d-'%os.path.getsize (filename)} Self.mode = ' ab ' SELF.R = Requests.get (self.url,stream=true,headers=self.headers) with open (filename, self.mode) as Cod                    E:for Chunk in Self.r.iter_content (chunk_size=1024): #边下载边存硬盘 if Chunk and Self.flag: Code.write (Chunk) Else:break Time.sleep (1) def cancel (self,filename ): #取消下载 self.flag=false time.sleep (1) if os.path.isfile (filename): os.remove (filename)

There's a bit more code to implement the interface, and it's not given here. All the source code has been uploaded to http://down.51cto.com/data/2445977, there is a need to download.

Thinking and summarizing

Cancel the download there spent a lot of time, has been tangled in how to force quit the download file thread, and finally found not forced to quit, directly in the download file function to increase the SELF.FLAG flag bit, when false can cause the thread to exit.
This small project also learned a lot of multithreading knowledge.

Python implementation Download interface (with progress bar, breakpoint resume, multi-threaded multi-task download, etc.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.