How to Replace Console Output with a Counter and Progress Bar in Python?

Patricia Arquette
Release: 2024-11-03 14:51:30
Original
143 people have browsed it

How to Replace Console Output with a Counter and Progress Bar in Python?

Replacing Console Output in Python

Python's versatile nature allows for custom console output to be tailored to specific needs. One common technique is creating dynamic console counters that update in place.

Query: Replacing Output with a Counter

To replace console output with a progress counter, a loop can be modified to display a status message after performing each iteration. Unlike the previous output, which included a new line for each status, this counter would update only the last displayed line.

Solution: Using 'r'

One simple solution involves inserting a carriage return character "r" before the new status message and avoiding any newline characters. This ensures that the string doesn't get shorter, making it a viable approach if the string is expected to remain consistent in length.

For example:

import sys

for i in range(5):
    sys.stdout.write("\rDoing thing %d" % i)
    sys.stdout.flush()
Copy after login

Enhanced Solution: Progress Bar

For more sophisticated progress displays, a progress bar can be implemented. The following code provides a simple progress bar function:

def start_progress(title):
    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()
Copy after login

The start_progress function initializes the progress bar with a title description. progress(x) updates the bar with the percentage completion (x). Finally, end_progress finishes the progress display.

The above is the detailed content of How to Replace Console Output with a Counter and Progress Bar 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!