Home > Backend Development > Python Tutorial > How to Create Console Counters in Python like C/C ?

How to Create Console Counters in Python like C/C ?

Linda Hamilton
Release: 2024-11-03 10:49:29
Original
397 people have browsed it

How to Create Console Counters in Python like C/C  ?

Console Counters in Python

Q: How can I create console counters in Python, similar to those found in C/C programs, where the output is replaced with an updating value?

A: Simple String Update:

An easy solution is to write "r" before the string and omit the newline character. If the string length remains consistent, this method can suffice.

Example:

<code class="python">sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()</code>
Copy after login

Advanced Progress Bar:

For a more sophisticated approach, consider a progress bar. Here's an example:

<code class="python">def start_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
    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()</code>
Copy after login

To use this progress bar, call start_progress(title) with a description of the operation, then call progress(x) with the percentage, and finally end_progress() to complete the operation.

The above is the detailed content of How to Create Console Counters in Python like C/C ?. 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