Home >Backend Development >Python Tutorial >How to Replace Console Output in Python?
Replace Console Output in Python
In Python, controlling the output to the console can be challenging, especially when you need to update only a portion of the displayed information. This question discusses a solution to replace the current console output with a concise progress counter.
A straightforward approach involves writing a backspace character ("r") followed by the new string without a newline character. By doing this, only the most recent line in the console is updated. This is shown in the code snippet below:
<code class="python">sys.stdout.write("\rDoing thing %i" % i) sys.stdout.flush()</code>
However, for a more sophisticated progress bar, you can implement a custom function to track the progress and display a dynamic bar based on the progress percentage. Here's an example:
<code class="python">def 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 progress_x = int(x * 40 // 100) sys.stdout.write("#" * (progress_x - progress_x)) sys.stdout.flush() def stop_progress(): sys.stdout.write("#" * (40 - progress_x) + "]\n") sys.stdout.flush()</code>
To use this function, call start_progress with the operation description, progress with the percentage, and finally stop_progress to display the complete progress bar in the console.
The above is the detailed content of How to Replace Console Output in Python?. For more information, please follow other related articles on the PHP Chinese website!