Before overwriting the same line, 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 above code may cause some momentary flicker. In your specific case, it is enough 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 it's even better to 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 always prefer the cursor after the last point:
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 the cursor to always be 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 because your shell remembers the remaining characters of the previous line if you overwrite only the first part of it.
source share