Home >Backend Development >Python Tutorial >How to Replace Static Console Output with Dynamic Counters in Python?
Replace Console Output with Dynamic Counters in Python
Tired of your Python console output flooding the screen? Let's explore how to create counters that update without overwriting previous lines.
One simple approach involves using "r" to return the cursor to the beginning of the current line, effectively replacing the existing output. This is an effective solution when your output length remains constant:
<code class="python">sys.stdout.write("\rDoing thing {}".format(i)) sys.stdout.flush()</code>
However, if your output length can vary, a more sophisticated solution is required. Consider this progress bar implementation:
<code class="python">def start_progress(title): sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41) sys.stdout.flush() def progress(x): x = int(x * 40 // 100) sys.stdout.write("#" * (x - progress_x)) sys.stdout.flush() def end_progress(): sys.stdout.write("#" * (40 - progress_x) + "]\n") sys.stdout.flush()</code>
This code allows you to display a customizable progress bar by calling start_progress, update it with progress(x) where x is the percentage, and finally end it with end_progress.
So, next time you want your console output to be more interactive and user-friendly, consider these techniques for creating dynamic counters in Python.
The above is the detailed content of How to Replace Static Console Output with Dynamic Counters in Python?. For more information, please follow other related articles on the PHP Chinese website!