Python shows the progress bar method _python

Source: Internet
Author: User

The example in this article describes how Python displays the progress bar, which is a very useful technique in Python programming. Share to everyone for your reference. The specific methods are as follows:

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

The answer is that print prints a \ n, a newline, so that the cursor moves to the beginning of the next line, and then the output, which is still retained by the STDOUT output, and ensures that we see the latest output below.

Progress bar Otherwise, we must again in situ output in order to ensure that he is a progress bar, otherwise the line is called a progress bar?

The simplest way is, after the output is finished, the cursor moved 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, formed an animation effect.

You can think of that escape character, that's \ 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.

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

#!/usr/bin/env python
#-*-coding=utf-8-*-
#Using GPL v2
#Author: ihipop@gmail.com
# #2010-10-27 22:07
"" "
Usage:
Just A Template
" "from
__future__ Import Division
 
import Sys,time
J = ' # '
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 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 you can not use + =, for example:

#!/usr/bin/env python
#-*-coding=utf-8-*-
#Using GPL v2
#Author: ihipop@gmail.com
#2010-10-27 22:07
"""
Usage:
Just A Template
"" "from
__future__ Import Division
 
import Sys,time
if __name__ = = ' __main __ ': For
  I in range (1,61):
    sys.stdout.write (' # ' + '-> ' + ' \b\b ')
    Sys.stdout.flush ()
    time.sleep (0.5)
Print

Cursor back 2, write a # and then back, write, to achieve the purpose of growth

But writing so much seems to be nonsense, in the ear often hear a word: that is not to repeat the wheel. In fact Python has rich hair lib to help you achieve this, you can put your mind to logical development without paying attention to these little details.

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

As shown in the following illustration:

Here is the basic use example:

#!/usr/bin/env python
#-*-coding=utf-8-*-
#Using GPL v2
#Author: ihipop@gmail.com
#2010-10-27 22:53
"""
Usage:
Just A Template
"" "from
__future__ Import Division
 
import Sys,time from
ProgressBar Import * Total
= 1000
 
#基本用法
progress = ProgressBar () for
I-Progress (range (total)):
 Time.sleep (0.01)
 
pbar = ProgressBar (). Start () for
I in range (1,1000):
  pbar.update (int (i/(TOTAL-1)) * ))
  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

#coding: utf-8 Import sys import time from ProgressBar import Animatedmarker, Bar, Bouncingbar, Counter, ETA, \ Filetran
Sferspeed, Formatlabel, percentage, \ ProgressBar, Reversebar, Rotatingmarker, simpleprogress, Timer examples = [] 
      def example (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.stdout.write (' \nskipping example.\n\n ') examples.append (wrapped) return wrapped @example def example0 (): PBA R = ProgressBar (Widgets=[percentage (), Bar ()], maxval=300). Start () for I (range): Time.sleep (0.01) pbar.up Date (i+1) Pbar.finish () @example def example1 (): widgets = [' Test: ', percentage (), ', Bar (Marker=rotatingmarker ()] , ', ETA (), ', Filetransferspeed ()] Pbar = ProgressBar (Widgets=widgets, maxval=10000000). Start () for I Range (1000000): # do Something Pbar.update (10*i+1) pbar.finish () @example def example2 (): Class Crazyfiletransferspeed (FILETRANSFERSP
    eed): "" "It's bigger between percent." " def update (self, pbar): If < Pbar.percentage () < 80:return ' bigger now ' + Filetransferspeed.updat E (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 () to I in Range (2000000): # do something Pbar.update (5*i+1) pbar.finish () @example def example3 (): Widgets = [Bar (' > '), ', ETA (), ', Reversebar (' < ')] Pbar = ProgressBar (widgets=wid Gets, maxval=10000000). Start () for I in Range (1000000): # do something Pbar.update (10*i+1) pbar.finish () @exa Mple def example4 (): 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,50): Time.sleep (0.2) pbar.update (i) pbar.finish () @example def example5 (): Pbar = ProgressBar (Widgets=[simpleprogress ()), maxval=17). Start () for I in Range (): Time.sleep (0.2) pbar.upd Ate (i + 1) pbar.finish () @example def example6 (): Pbar = ProgressBar (). Start () for I in Range (m): Time.sleep ( 0.01) Pbar.update (i + 1) pbar.finish () @example def example7 (): Pbar = ProgressBar () # ProgressBar can guess MAXV
  Al automatically. For I in Pbar (range): Time.sleep (0.01) @example def example8 (): Pbar = ProgressBar (maxval=80) # ProgressBar can
  ' t guess Maxval. For I in Pbar ((I for I in Range ()): Time.sleep (0.01) @example def example9 (): Pbar = ProgressBar (widgets=[' Worki NG: ', Animatedmarker ()]) for I-in Pbar ((I for I in Range ()): Time.sleep (.) @example def ExamplE10 (): widgets = [' Processed: ', Counter (), ' lines (', Timer (), ') '] Pbar = ProgressBar (widgets=widgets) for I in P Bar ((I for I in Range ()): Time.sleep (0.1) @example def example11 (): Widgets = [Formatlabel (' Processed:% (value) D lines (in:% (elapsed) s) "] Pbar = ProgressBar (widgets=widgets) for I-Pbar ((I for I in Range ()): Time.slee P (0.1) @example def example12 (): widgets = [' Balloon: ', Animatedmarker (markers= '. oo@* ')] Pbar = ProgressBar (widgets =widgets) for I-Pbar ((I for I in Range ()): Time.sleep (0.3) @example def example13 (): # Your may need Python 3.x to correctly try:widgets = [' Arrows: ', Animatedmarker (markers= ' ←↖↑↗→↘↓↙ ')] Pbar = ProgressBar (wid Gets=widgets) for I-Pbar ((I for I in Range ()): Time.sleep (0.3) except UnicodeError:sys.stdout.write (' Un Icode error:skipping Example ') @example def example14 (): # You could need Python 3.x to the this correctly try:wi Dgets = [' Arrows: ', AniMatedmarker (markers= ' ◢◣◤◥ ')] Pbar = ProgressBar (widgets=widgets) for I-In-Pbar ((I for I in Range ()): Time . Sleep (0.3) except UnicodeError:sys.stdout.write (' Unicode error:skipping example ') @example def Example15 (): # May need Python 3.x to correctly try:widgets = [' Wheels: ', Animatedmarker (markers= ' ◐◓◑◒ ')] Pbar = Pro Gressbar (widgets=widgets) for I-Pbar ((I for I in Range ()): Time.sleep (0.3) except UnicodeError:sys.stdo Ut.write (' Unicode error:skipping example ') @example def example16 (): Widgets = [Formatlabel (' Bouncer:value% (value) d

-'), Bouncingbar ()] Pbar = ProgressBar (widgets=widgets) for I in Pbar ((I for I in range (180)): Time.sleep (0.05) @example def example17 (): Widgets = [Formatlabel (' animated Bouncer:value% (value) d-'), Bouncingbar (Marker=ro Tatingmarker ())] Pbar = ProgressBar (widgets=widgets) for I-In-Pbar ((I for I in range (180)): Time.sleep (0.05) @e
Xample def example18 ():  Widgets = [Percentage (), ', Bar (), ', ETA (), ', Adaptiveeta ()] Pbar = ProgressBar (widget S=widgets, maxval=500) Pbar.start () for I in range: Time.sleep (0.01 + (i <) * 0.01 + (i > 400) * 0. 9) Pbar.update (i + 1) pbar.finish () @example def example19 (): Pbar = ProgressBar () for I and Pbar ([]): Pass PBA 

R.finish () try:for example in Examples:example () except KeyboardInterrupt:sys.stdout (' \nquitting examples.\n ') Progress Bar Usage Example

Send a second class:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: ihipop@gmail.com #2010 -10-30 13:59 "" "Usage:just A Template "" "Class Progressbarclass:def __init__ (self, Finalcount, progresschar=none): Import sys Self.finalco Unt=finalcount self.blockcount=0 # # If caller passed me a character to-use on the # progress bar (lik E "*").
    If not with the Block # character which makes it look like a real progress # bar. # If not PROGRESSCHAR:SELF.BLOCK=CHR (178) Else:self.block=progresschar # get pointer to SYS.STD
    Out so I can use the Write/flush # methods to display the progress bar. # self.f=sys.stdout # If the final count is zero, don ' t start the progress gauge # if not self.final Count: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 done # if SELF.FINALCOUNT:PERCENTC Omplete=int (Round (100*count/self.finalcount)) if PercentComplete < 1:percentcomplete=1 Else:percentco mplete=100 #print "percentcomplete=", PercentComplete blockcount=int (PERCENTCOMPLETE/2) #print "Blockcou Nt= ", Blockcount if Blockcount > Self.blockcount:for i in Range (Self.blockcount,blockcount): SELF.F.W Rite (Self.block) Self.f.flush () if PercentComplete = = 100:self.f.write ("\ n") Self.blockcount=blo Ckcount return If __name__ = = "__main__": From Time Import sleep Pb=progressbarclass (8, "*") count=0 while C

 Ount<9:count+=1 pb.progress (count) sleep (0.2)

In addition, section 11.1 of the Python Cookbook provides a good progress bar class with the following code:

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. Write (' \ n------------------% Progress-------------------1\n ') self.f.write (' 1 2 3 4 5 6 7 8 9 0\n ') s Elf.f.write ('----0----0----0----0----0----0----0----0----0----0\n ') def progress (self, count): Count = min (count, se Lf.finalcount) If self.finalcount:percentcomplete = Int (round (100.0*count/self.finalcount)) if percentcom Plete < 1:percentcomplete = 1 else:percentcomplete=100 blockcount = Int (PERCENTCOMPLETE//2) if Bloc 
    Kcount <= 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 = Progre 
  Ssbar (pb.progress) sleep (0.3) pb.progress (0.3) pb.progress (m) sleep (0.3) pb.progress (100)

 Print "Testing 1:" PB = ProgressBar (1) pb.progress (1)

The results of the operation are shown in the following illustration:

I hope this article will help you with your study of Python programming.

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.