Python Implementation download progress bar (without GUI interface)

Source: Internet
Author: User

Talk not much, first

This Python code can be implemented to get the downloaded file name, download the file size, download speed, etc.

Code key points:

1, about the download file name acquisition: The code is used in two ways to obtain:
(1) Through the Content-disposition property, this property is used as an identification field for the downloaded file, which stores the download filename

(2) directly through the link to obtain, for example: Sw.bos.baidu.com/sw-search-sp/software/8b23f8846df3d/baidumusicsetup.exe file is directly behind the file name.
2, about the download file size acquisition: directly from the HTTP response information, in the Content-length

3, Requests.get (URL) is downloaded in memory by default, the download is completed to save to the hard disk, so that the current download progress is not available, so to set the side to the bottom of the storage drive

    def downfile(self,filename):  #下载文件        self.r = requests.get(self.url,stream=True)        with open(filename, "wb") as code:            for chunk in self.r.iter_content(chunk_size=1024): #边下载边存硬盘                if chunk:                    code.write(chunk)
Attach Python code:
Import threadingimport osimport requestsimport timeimport reimport urllibdef view_bar (num, total): #显示进度条 rate = num/t Otal rate_num = Int (rate *) Number=int (50*rate) r = ' \r[%s%s]%d%% '% ("#" *number, "" * (50-number), Rate_num,        Print ("\ r {}". Format (R), end= "") #\r back to the beginning of the line Class Getfile (): #下载文件 def __init__ (self,url): Self.url=url        #self. Filename=filename self.re=requests.head (url,allow_redirects=true) #运行head方法时重定向 def getsize (self): Try:self.file_total=int (self.re.headers[' content-length ') #获取下载文件大小 return Self.file_tot Al Except:print (' cannot get download file Size ') exit () def getfilename (self): #获取默认下载文件名 filename= ' ' If ' content-disposition ' in Self.re.headers:n=self.re.headers.get (' Content-disposition '). Split (' Name=            ') [1] filename=urllib.parse.unquote (n,encoding= ' UTF8 ') elif os.path.splitext (self.re.url) [1]!= ': Filename=os.path.baSENAME (Self.re.url) return filename def downfile (self,filename): #下载文件 SELF.R = Requests.get (self.url,st Ream=true) with open (filename, "WB") as Code:for Chunk in Self.r.iter_content (chunk_size=1024): #边下载边存硬 Disk if Chunk:code.write (chunk) time.sleep (1) #print ("\ n Download Complete") def DOWNP        Rogress (self,filename): Self.filename=filename self.file_size=0 self.file_total=self.getsize ()                 While Self.file_size<self.file_total: #获取当前下载进度 time.sleep (1) if Os.path.exists (self.filename): Self.down_rate= (Os.path.getsize (self.filename)-self.file_size)/1024/1024 self.down_time= (SE Lf.file_total-self.file_size)/1024/1024/self.down_rate print ("" +str ('%.2f '%self.down_rate+ "MB/S"), end= ""            ) self.file_size=os.path.getsize (self.filename) print ("" +str (int (self.down_time)) + "s", end= "") Print ("" +stR ('%.2f '% (self.file_size/1024/1024)) + "MB", end= "") View_bar (Self.file_size, self.file_total) if __name__ = = ' __m ain__ ': url = input ("Input URL:") While not Re.match (' ^ (https?| FTP)://.+$ ', url): url = input ("URL format is wrong, please reenter:") file1=getfile (URL) file_total=file1.getsize () filename=file 1.getfilename () If filename== ': filename=input (' cannot get the download file name, please enter it yourself: ') print ("The downloaded file is:" +str ('%.2f '% (file_total /1024/1024) + "MB") print ("Start download file:" +filename) T1 = Threading. Thread (target=file1.downfile,args= (filename,)) T1.start () file1.downprogress (filename)

The source code is also uploaded to Http://down.51cto.com/data/2445550

Summary and follow-up

This time is a Python class to write code, write a little bit less accustomed to, but change or maintain the code, it feels very convenient.
This code is only run under the DOS command line, and the next task is to use Tkinter to add GUI interface

Python Implementation download progress bar (without GUI interface)

Related Article

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.