Home >Backend Development >Python Tutorial >How to Overwrite Console Output in Python?
Overriding Console Output in Python
In programming, it's often desirable to display progress information to users while executing time-consuming tasks. One popular technique is to update a progress bar or counter in the console. This article explores how to achieve this in Python.
Replacing Console Output
A simple approach to replacing console output is to use the "r" escape sequence, which returns the cursor to the beginning of the current line. By writing "r" before the updated string and omitting a newline, you can effectively overwrite the previous output.
<code class="python">import sys for i in range(10): sys.stdout.write("\rDoing thing %i" % i) sys.stdout.flush()</code>
This will continuously overwrite the console with the latest iteration in the loop.
Progress Bars
For a more advanced progress indicator, you can use the following function:
<code class="python">def start_progress(title): sys.stdout.write(title + ": [" + "-" * 40 + "]") 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 function takes a title as input and displays a progress bar in the console. The progress function updates the progress percentage, while the end_progress function completes the progress bar.
Call Sequence
To use the progress bar, call start_progress to initialize it, then call progress multiple times to update the percentage. Finally, call end_progress to complete the progress bar.
<code class="python">start_progress("My Long Task") progress(50) progress(75) end_progress()</code>
The above is the detailed content of How to Overwrite Console Output in Python?. For more information, please follow other related articles on the PHP Chinese website!