Print runtime processing in Python

I wrote this simple processing_flush function to print a sequence of dots (given by an index) to check if my software is processing my data and, ultimately, 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 the points are printed for the first time (for example: Processing .... if the index is 5), the cursor does not start from zero.

+4
source share
1 answer

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.

+6
source

All Articles