Progress Bar

Indices and tables

Background

It is beneficial to provide users of your program with status of a long running task. One method to do this is to use a progress bar.

There are likely multiple places to use a progress bar in your program and multiple programs you would likely want to use it in. As a programmer, you should therefore keep re-usability in mind. However, for this exercise, just getting a bar to print and update will be sufficient.

There are packages on the web that you can download from PyPI that let you do just that. But, this is a course to learn, not to copy, so, don’t cheat. ;)

Exercise

There are different levels to this problem. Break the problem up and approach them sequentially:

  1. Implement code that draws a progress bar to the screen and updates it along the way.
  2. Add code to compute the % complete and draw it at the start or end of the bar.
  3. Add additional code so that the progress bar re-draws over itself and does not consume a new line each time it updates.
  4. Add additional code so that the bar is a different color than the % complete value.

You should package it as a function in a way that lets you call it standalone or from another program.

Hints

  • You will undoubtedly have to loop within your code. Below is some boilerplate for loops:

    # Assuming you want to loop NUM_STEPS times
    for i in range(0, NUM_STEPS+1):
        #
        # Put your code here
        #
    
  • The terminal has crazy functionality most people are not aware of. It is exposed via escape codes, which you can read about here. Keep in mind, Jupyter is NOT a terminal, and you won’t be able to get it to NOT print a new line for each cycle of the progress bar. Use PyCharm or the interpreter instead.

  • Checkout the time module for methods to pause execution temporarily.

  • You can force the text stream to print to the screen by using the following code:

    # At the top of your source file, bring in the sys package
    import sys
    
    #
    # ...your code somewhere here...
    #
    
    # Within your code, to force the standard out text stream to display
    sys.stdout.flush()
    

Solution

When you are ready to see one possible solution, try this file