Python implementation console progress bar function

Source: Internet
Author: User
The example in this paper describes how Python displays the progress bar and is a very useful technique in Python programming. Share to everyone for your reference. Here's how:

First, what is the difference between the progress bar and the general print?

The answer is that print will output a \ n, a newline character, so that the cursor moves to the beginning of the next line, then the output, something that was previously output through the stdout remains, and we see the latest output below.

Progress bar Otherwise, we must re-in-situ output to ensure that he is a progress bar, or change the line how to still call the progress bar?

The simplest way is, after the output is finished, the cursor moves to the beginning of the line, continue to be there to output a longer progress bar can be achieved, the new longer progress bar to the old short cover, the formation of animation effect.

Can think of that escape character, that is \ r.

The escape character R can move the cursor to the beginning of the line without wrapping, and the escape character n moves the cursor to the beginning of the line and wraps it.

In Python, the output stdout (standard output) can be used Sys.stdout.write
For example:

Python

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2 "" Usage:just A Template "" "from __future__ Import Division Import Sys,timej = ' # ' if __name__ = = ' __main__ ': for  I in range (1,61):    J + = ' # '    sys.stdout.write (str (int (I/60) *100 ))+'% ||' +j+ ', ' + ' \ R ')    Sys.stdout.flush ()    time.sleep (0.5) print

The second way of thinking is to use the escape character \b
Escape character \b is the backspace key, that is, the output of the cursor back to the grid, so that you can not use + =, for example:

Python

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2 "" Usage:just A Template "" "from __future__ Import Division Import Sys,timeif __name__ = = ' __main__ ': for  I in range (1,61):    sys.stdout.write (' # ' + ' + ' + ' \b\b ')    Sys.stdout.flush ()    time.sleep (0.5) print

The cursor back 2, write a # back, then write, to achieve the purpose of growth

But to write so much seems to be nonsense, in the ear often hear a word: that is, do not repeat the wheel. In fact Python has a rich set of LIB to help you implement this thing, you can put your mind on logic development without paying attention to these small details

The following is to introduce this class "ProgressBar" (http://code.google.com/p/python-progressbar/), using Easy_install can easily install the class library, in fact, a file, Put it in the same directory under the file and you can import it directly.

As shown in the following:

Here is an example of basic use:

Python

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2 "" Usage:just A Template "" "from __future__ Import Division Import Sys,timefrom ProgressBar Import *total = #基本用法progress = ProgressBar () for I in Progress (range): Time.sleep (0.0 1) Pbar = ProgressBar (). Start () for I in Range (1,1000):  pbar.update (int ((i/(TOTAL-1)) *100)  Time.sleep (0.01) Pbar.finish () #高级用法widgets = [' Progress: ', Percentage (), ', Bar (Marker=rotatingmarker (' >-= ')),      ', ETA (), ', Filetransferspeed ()]pbar = ProgressBar (Widgets=widgets, maxval=10000000). Start () for I in Range (1000000): # do something Pbar.update (10*i+1) time.sleep (0.0001) pbar.finish ()

Official Example: http://code.google.com/p/python-progressbar/source/browse/progressbar/examples.py

Python

# coding:utf-8import Sysimport timefrom ProgressBar import Animatedmarker, Bar, Bouncingbar, Counter, ETA, \ Filetransfer Speed, Formatlabel, Percentage, \ ProgressBar, Reversebar, Rotatingmarker, \ simpleprogress, Timer examples = [] def exa      Mple (fn): Try:name = ' Example%d '% int (fn.__name__[7:]) except:name = fn.__name__ def wrapped (): try: Sys.stdout.write (' Running:%s\n '% name) fn () sys.stdout.write (' \ n ') except KeyboardInterrupt:sys.stdo Ut.write (' \nskipping example.\n\n ') examples.append (wrapped) return wrapped @exampledef example0 (): Pbar = ProgressBar (Widgets=[percentage (), Bar ()], maxval=300). Start () for I in range: Time.sleep (0.01) pbar.update (i + 1) pbar.  Finish () @exampledef example1 (): widgets = [' Test: ', Percentage (), ', Bar (Marker=rotatingmarker ()), ', ETA (),  ", Filetransferspeed ()] Pbar = ProgressBar (Widgets=widgets, maxval=10000000). Start () for I in Range (1000000): # do Something Pbar.updatE (Ten * i + 1) pbar.finish () @exampledef example2 (): Class Crazyfiletransferspeed (Filetransferspeed): "" "" It's bigger B     Etween and percent. "" " def update (self, pbar): If < Pbar.percentage () < 80:return ' bigger now ' + filetransferspeed.update ( Self, pbar) Else:return filetransferspeed.update (self, pbar) widgets = [Crazyfiletransferspeed (), ' <&lt ;< ', Bar (), ' >>> ', Percentage (), ', ETA ()] Pbar = ProgressBar (Widgets=widgets, maxval=10000000) # Maybe do something pbar.start () for I in Range (2000000): # Do something pbar.update (5 * i + 1) pbar.finish () @exa Mpledef Example3 (): Widgets = [Bar (' > '), ', ETA (), ', Reversebar (' < ')] Pbar = ProgressBar (Widgets=widgets, Max val=10000000). Start () for I in Range (1000000): # do something pbar.update (Ten * i + 1) pbar.finish () @exampledef ex Ample4 (): widgets = [' Test: ', Percentage (), ', Bar (marker= ' 0 ', left= ' [', right= '] '), ', ETA (), ', Filetransferspeed ()] Pbar = ProgressBar (widgets=widgets, maxval=500) Pbar.start () for I in range (100, 500 + 1, 5 0): Time.sleep (0.2) pbar.update (i) pbar.finish () @exampledef example5 (): Pbar = ProgressBar (widgets=[simpleprogres S ()], maxval=17). Start () for I in range: Time.sleep (0.2) pbar.update (i + 1) pbar.finish () @exampledef Example6 (): Pbar = ProgressBar (). Start () for I in range: Time.sleep (0.01) pbar.update (i + 1) pbar.finish () @exampled  EF Example7 (): Pbar = ProgressBar () # ProgressBar can guess maxval automatically. For I in Pbar (range): Time.sleep (0.01) @exampledef example8 (): Pbar = ProgressBar (maxval=80) # ProgressBar can ' t g  Uess Maxval. For I in Pbar ((I-I in range)): Time.sleep (0.01) @exampledef example9 (): Pbar = ProgressBar (widgets=[' working: ', Animatedmarker ()])) for I in Pbar ((I-I in range): Time.sleep (.) @exampledef Example10 (): widgets = [' Pro cessed: ', Counter (), ' lines (', Timer (), ') ' Pbar = ProgressBar (widgets=widgets) for I in Pbar ((I-I in range): Time.sleep (0.1) @exampledef example11 (): Widgets = [Formatlabel (' Processed:% (value) d lines (in:% (elapsed) s)] "Pbar = ProgressBar (widgets=widgets) for I in PB AR ((I for I in range): Time.sleep (0.1) @exampledef example12 (): widgets = [' Balloon: ', Animatedmarker (markers= ') . oo@* ')] Pbar = ProgressBar (widgets=widgets) for I in Pbar ((I-I in range)): Time.sleep (0.3) @exampledef exam    Ple13 (): # need Python 3.x to see this correctly try:widgets = [' Arrows: ', Animatedmarker (markers= ' ←↑→↓ ')] Pbar = ProgressBar (widgets=widgets) for I in Pbar ((I-I in range)): Time.sleep (0.3) except Unicodeerror : Sys.stdout.write (' Unicode error:skipping example ') @exampledef example14 (): # You could need Python 3.x to see this C orrectly try:widgets = [' Arrows: ', Animatedmarker (markers= ' ◢◣◤◥ ')] Pbar = ProgressBar (widgets=widgets) for I I n Pbar ((i-I in range()): Time.sleep (0.3) except UnicodeError:sys.stdout.write (' Unicode error:skipping example ') @exampledef exam    Ple15 (): # need Python 3.x to see this correctly try:widgets = [' Wheels: ', Animatedmarker (markers= ' ◐◓◑◒ ')] Pbar = ProgressBar (widgets=widgets) for I in Pbar ((I-I in range)): Time.sleep (0.3) except Unicodeerror : Sys.stdout.write (' Unicode error:skipping example ') @exampledef Example16 (): Widgets = [Formatlabel (' Bouncer:value % (value) d-'), Bouncingbar ()] Pbar = ProgressBar (widgets=widgets) for I in Pbar ((I-I in range)): Time.sleep (0.05) @exampledef Example17 (): Widgets = [Formatlabel (' animated Bouncer:value% (value) d-'), Bouncingbar (marker =rotatingmarker ())] Pbar = ProgressBar (widgets=widgets) for I in Pbar ((I-I in range)): Time.sleep (0.05) @ex Ampledef Example18 (): Widgets = [Percentage (), ', Bar (), ', ETA (), ', Adaptiveeta ()] Pbar = P Rogressbar (Widgets=widgeTS, maxval=500) Pbar.start () for I in range: Time.sleep (0.01 + (i <) * 0.01 + (i > +) * 0.9) Pbar . Update (i + 1) pbar.finish () @exampledef example19 (): Pbar = ProgressBar () for I in Pbar ([]): Pass Pbar.finish () TR y:for example in Examples:example () except KeyboardInterrupt:sys.stdout (' \nquitting examples.\n ')

To send a second class:

Python

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2 "" Usage:just A Template "" "Class Progressbarclass:def __init__ ( Self, Finalcount, progresschar=none): Import sys self.finalcount=finalcount self.blockcount=0 # # See if CA Ller passed me a character to use on the # progress bar (like "*").    If not use the Block # character This makes it look like a real progress # bar. # If not PROGRESSCHAR:SELF.BLOCK=CHR (178) Else:self.block=progresschar # # Get Pointer to Sys.stdout    So I can use the Write/flush # methods to display the progress bar.  # self.f=sys.stdout # If the final count is zero, and don ' t start the progress gauge # if not Self.finalcount     : Return self.f.write (' \ n-------------------% Progress-------------------\ n ') return def Progress (self, count): # # Make sure I don ' t try to go off the end (e.g. >100%) # Count=min (count, Self.finalcount) # # If Finalcount is zero, I ' m do #   If Self.finalcount:percentcomplete=int (round (100*count/self.finalcount)) if PercentComplete < 1:PERCENTC omplete=1 else:percentcomplete=100 #print "percentcomplete=", PercentComplete blockcount=int (percentcomplet E/2) #print "blockcount=", Blockcount if Blockcount > Self.blockcount:for i in range (SELF.BLOCKCOUNT,BLOCKCO UNT): Self.f.write (Self.block) Self.f.flush () if PercentComplete = = 100:self.f.write ("\ n") Self.bloc  Kcount=blockcount return If __name__ = = "__main__": From Time Import sleep Pb=progressbarclass (8, "*") count=0 while Count<9:count+=1 pb.progress (count) sleep (0.2)

In addition, the Python Cookbook 11.1 section also provides a good progress bar class, the code is as follows:

Python

Import SYS class ProgressBar (object): Def __init__ (self, finalcount, block_char= '. '): Self.finalcount = Finalcount Self.blockcount = 0 Self.block = Block_char self.f = sys.stdout if not Self.finalcount:return SELF.F.WR ITE (' \ n------------------% Progress-------------------1\n ') self.f.write (' 1 2 3 4 5 6 7 8 9 0\n ') self.f.write ('-    ---0----0----0----0----0----0----0----0----0----0\n ') def progress (self, count): Count = Min (count, Self.finalcount)        if self.finalcount:percentcomplete = Int (Round (100.0 * count/self.finalcount)) If PercentComplete < 1: PercentComplete = 1 Else:percentcomplete = blockcount = Int (PercentComplete//2) if Blockcount <= Self.blockcount:return for I in range (Self.blockcount, Blockcount): Self.f.write (Self.block) self.f  . Flush () Self.blockcount = Blockcount if PercentComplete = = 100:self.f.write ("\ n") if __name__ = = "__main__": From time import sleep PB = ProgressBar (8, "*") for count in range (1, 9): Pb.progress (count) sleep (0.2) PB = ProgressBar (+) Pb.progre SS (pb.progress) sleep (0.3) sleep (0.3) pb.progress (0.3) pb.progress (+) print "Testing 1:" PB = P Rogressbar (1) pb.progress (1)

The results of the operation are as follows:

I hope this article is helpful to the study of Python program design.

  • 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.