Progress Bars in python

Fredrik Lundh fredrik at pythonware.com
Wed Jul 12 06:49:42 EDT 2006


Hari Sekhon wrote:

>   I've written a script which backs up a huge bunch of files, but I
> don't want the script to output the file names as it does this as it
> clutters the screen, I only output errors.
>
> So in order to see that the script is working and not stuck, I'd like to
> implement some kind of progress bar or something, perhaps like the
> spinning thing that you often see in linux or freebsd consisting of
> switching / - \ | on the spot to get the appearance of a spinning
> bar.... I can figure out that the spinning bar is done by switching
> these four chars but I don't know how they get each char to replace the
> last one instead of printing them in succession.

use backspace ("\b") or carriage return ("\r") to move the cursor backwards.

minimal example:

    import time, sys

    for i in range(100+1):
        sys.stdout.write("\r%c %d%% done..." % ("|/-\\"[i%4], i))
        sys.stdout.flush()
        time.sleep(0.2)

maximal example (also see the comments):

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473899

</F> 






More information about the Python-list mailing list