Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

Python to print out status bar and percentage

To implement a status bar like below:

[==========                ]  45%
[================          ]  60%
[==========================] 100%

I want to this to be printed out to stdout, and keep refreshing it, not print to another line. How to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The ' ' character (carriage return) resets the cursor to the beginning of the line and allows you to write over what was previously on the line.

from time import sleep
import sys

for i in range(21):
    sys.stdout.write('
')
    # the exact output you're looking for:
    sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
    sys.stdout.flush()
    sleep(0.25)

I'm not 100% sure if this is completely portable across all systems, but it works on Linux and OSX at the least.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...