print a progress-bar processing in Python

printing, progress-bar, python

Solution

Before you overwrite the same line again you need to clear at least the positions where the dots are with spaces.

def processing_flush(n, index=5):
    sys.stdout.write("\rProcessing %s" % (index * " "))
    sys.stdout.write("\rProcessing %s" % ((n % index)* "."))
    sys.stdout.flush()

The code above may lead to some brief flicker. In your specific case it is sufficient to clear the line when `n % index` becomes 0:

def processing_flush(n, index=5):
    if n % index == 0:
        sys.stdout.write("\rProcessing %s" % (index * " "))
    sys.stdout.write("\rProcessing %s" % ((n % index)* "."))
    sys.stdout.flush()

Or even better always write `index-1` characters:

def processing_flush(n, index=5):
    sys.stdout.write("\rProcessing %s%s" % ((n % index)* ".", (index - 1 - (n % index))* " "))
    sys.stdout.flush()

Edit 1: Or if you prefer to have the cursor always after the last dot:

def processing_flush(n, index=5):
    sys.stdout.write("\rProcessing %s%s" % ((n % index)* ".", (index - 1 - (n % index))* " "))
    sys.stdout.write("\rProcessing %s" % ((n % index)* "."))
    sys.stdout.flush()

Edit 2: Or if you prefer to have the cursor always at the beginning of the line:

def processing_flush(n, index=5):
    sys.stdout.write("Processing %s%s\r" % ((n % index)* ".", (index - 1 - (n % index))* " "))
    sys.stdout.flush()

The reason is that your shell remembers the remaining characters of the previous line if you overwrite just the first part of it.

Problem

I wrote this simple function "processing_flush" in order to print a sequence of points (given by index) to test if my software is processing my data and eventually the speed. The total size of my data is unknown. ``` import sys import time def processing_flush(n, index=5): sys.stdout.write("\rProcessing %s" % ((n % index)* ".")) sys.stdout.flush() for n in xrange(20): processing_flush(n, index=5) time.sleep(1) ``` The problem that i cannot fix is when all points are printed the first time (ex: Processing .... if index is equal to 5) the cursor doesn't start from zero.

Original source