Console Counters in Python
Q: How can I create console counters in Python, similar to those found in C/C programs, where the output is replaced with an updating value?
A: Simple String Update:
An easy solution is to write "r" before the string and omit the newline character. If the string length remains consistent, this method can suffice.
Example:
<code class="python">sys.stdout.write("\rDoing thing %i" % i) sys.stdout.flush()</code>
Advanced Progress Bar:
For a more sophisticated approach, consider a progress bar. Here's an example:
<code class="python">def start_progress(title): global progress_x sys.stdout.write(title + ": [&" + "-" * 40 + "]" + chr(8) * 41) sys.stdout.flush() progress_x = 0 def progress(x): global progress_x x = int(x * 40 // 100) sys.stdout.write("#" * (x - progress_x)) sys.stdout.flush() progress_x = x def end_progress(): sys.stdout.write("#" * (40 - progress_x) + "]\n") sys.stdout.flush()</code>
To use this progress bar, call start_progress(title) with a description of the operation, then call progress(x) with the percentage, and finally end_progress() to complete the operation.
The above is the detailed content of How to Create Console Counters in Python like C/C ?. For more information, please follow other related articles on the PHP Chinese website!