Home > Backend Development > Python Tutorial > How to Overwrite Console Output in Python?

How to Overwrite Console Output in Python?

Barbara Streisand
Release: 2024-11-02 22:08:30
Original
843 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template