Showing Progress Bar

Ned Batchelder ned at nedbatchelder.com
Sat Nov 23 12:47:12 CET 2013


On Saturday, November 23, 2013 6:36:28 AM UTC-5, Himanshu Garg wrote:
> I want to show simple dots while my program copies the files.  I have found the code like:
> 
> for i in range(10):
>     print '.',
>     time.sleep(1)
> 
> But this will execute ten times as it is predefined and the task to copy will execute after or before this loop based on the location I have placed my line to copy the files using shutil.copy().
> 
> I want that the files should be copied and in parallel the progress should be shown and when the files are copied, the progress should exit.

Stdout is buffered, meaning it will wait for a newline, or for some large amount of output, before actually outputting the characters to the screen.  Use the flush method to force it to be output now.  Writing to sys.stdout directly also lets you avoid the space that a print-comma gives you:

    for i in range(10):
        sys.stdout.write(".")
        sys.stdout.flush()
        time.sleep(1)
    sys.stdout.write("\n")

--Ned.



More information about the Python-list mailing list