bobber205 bobber205 - 7 months ago 51
Python Question

Text Progress Bar in the Console

Is there a good way to do the following?

I wrote a simple console app to upload and download files from an FTP server using the ftplib.

Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.

But I don't want to erase all the text that's been printed to the console. (Doing a "clear" and then printing the updated percentage.)

Answer

I've been using a modified version of @Vladimir Ignatyev's code posted above and loving it : )

import sys as Sys
# Print iterations progress
def printProgress (iteration, total, prefix = '', suffix = '', decimals = 2, barLength = 100):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
    """
    filledLength    = int(round(barLength * iteration / float(total)))
    percents        = round(100.00 * (iteration / float(total)), decimals)
    bar             = '#' * filledLength + '-' * (barLength - filledLength)
    Sys.stdout.write('%s [%s] %s%s %s\r' % (prefix, bar, percents, '%', suffix)),
    Sys.stdout.flush()
    if iteration == total:
        print("\n")

# 
# Sample Usage
# 

items = ["a", "b", "c", "d", "e"]
i     = 0
l     = len(items)

# Initial call to print 0% progress
printProgress(i, l, prefix = 'Progress:', suffix = 'Complete', barLength = 50)
for item in items:
    # Do stuff...
    # Update Progress Bar
    i += 1
    printProgress(i, l, prefix = 'Progress:', suffix = 'Complete', barLength = 50)

# Sample Output
Progress: [#############################################-----] 90.0% Complete