Showing Progress Bar

Frank Millman frank at chagford.com
Sat Nov 23 07:11:46 EST 2013


"Himanshu Garg" <hgarg.india at gmail.com> wrote in message 
news:b4b7cf70-07fa-455a-b01f-cb69b9402bc0 at googlegroups.com...
>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.

Ned has shown how to view the dots as they are printed, but has not 
addressed the 'parallel' aspect.

Here is one approach, which uses the threading module to print the dots in a 
separate thread while the main thread does the copying.

import sys
import threading

class ProgressBar(threading.Thread):
    """
    In a separate thread, print dots to the screen until terminated.
    """

    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()

    def run(self):
        event = self.event  # make local
        while not event.is_set():
            sys.stdout.write(".")
            sys.stdout.flush()
            event.wait(1)  # pause for 1 second
        sys.stdout.write("\n")

    def stop(self):
        self.event.set()

Before starting the copy -

    progress_bar = ProgressBar()
    progress_bar.start()

When the copy is finished -

    progress_bar.stop()
    progress_bar.join()

HTH

Frank Millman






More information about the Python-list mailing list