DanielTA DanielTA - 7 months ago 9
Python Question

Python: Run a progess bar and work simultaneously?

I want to know how to run a progress bar and some other work simultaneously, then when the work is done, stop the progress bar in Python (2.7.x)

import sys, time
def progress_bar():
while True:
for c in ['-','\\','|','/']:
sys.stdout.write('\r' + "Working " + c)
sys.stdout.flush()
time.sleep(0.2)

def work():
*doing hard work*


How would I be able to do something like:

progress_bar() #run in background?
work()
*stop progress bar*
print "\nThe work is done!"

Answer

You could run a thread in the background using the threading module. For example:

def run_progress_bar(finished_event):
    chars = itertools.cycle(r'-\|/')
    while not finished_event.is_set():
        sys.stdout.write('\rWorking ' + next(chars))
        sys.stdout.flush()
        finished_event.wait(0.2)


# somewhere else...
finished_event = threading.Event()
progress_bar_thread = threading.Thread(target=run_progress_bar, args=(finished_event,))
progress_bar_thread.start()
# do stuff
finished_event.set()
progress_bar_thread.join()