Posted By

gdvickery on 12/30/09


Tagged

bar python cli progress


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

duke
delpy
tfoutz99
vkolev
dgk


Python CLI (Command Line) Progress Bar


 / Published in: Python
 

This is a function that will show a progress bar of the given percentage. Useful when performing time consuming tasks.

  1. import sys
  2. import time
  3. import math
  4.  
  5. # Output example: [======= ] 75%
  6.  
  7. # width defines bar width
  8. # percent defines current percentage
  9. def progress(width, percent):
  10. marks = math.floor(width * (percent / 100.0))
  11. spaces = math.floor(width - marks)
  12.  
  13. loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']'
  14.  
  15. sys.stdout.write("%s %d%%\r" % (loader, percent))
  16. if percent >= 100:
  17. sys.stdout.write("\n")
  18. sys.stdout.flush()
  19.  
  20. # Simulate doing something...
  21. for i in xrange(100):
  22. progress(50, (i + 1)) # +1 because xrange is only 99
  23. time.sleep(0.1) # Slow it down for demo

Report this snippet  

You need to login to post a comment.