Progress-bar in python

Today I needed a progressbar for one of my python scripts. After looking for some sophisticated tools like the package progressbar I decided to try by myself something less complex.

The following code is the compacted-result:

from time import sleep
import sys

for i in range(21):
    sys.stdout.write('r')
    sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
    sys.stdout.flush()
    # Do the n-iteration of the job here 
    sleep(0.25)

    # The job was finished, let them know
    sys.stdout.write('r')
    sys.stdout.write("[%20s] 100%%: Donen" % ('=' * 20))

So… I use the sys.stdout.write instead of the print and I combine it with the character \r. With that I place the cursor at the beginning of the line and then I rewrite the whole line.

At the end I redo the same adding the message Done after the progressbar.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: