Skip to content

Instantly share code, notes, and snippets.

@wllhf
Last active May 20, 2016 17:58
Show Gist options
  • Save wllhf/34672b96c8a8241a9fdb to your computer and use it in GitHub Desktop.
Save wllhf/34672b96c8a8241a9fdb to your computer and use it in GitHub Desktop.
Python progress bar.
import sys
import time
import threading
import multiprocessing
global_status = {"text": "NA",
"fraction": 0.0,
"ref_time": 0}
BAR_SIZE = 40
D_SECS = 86400
H_SECS = 3600
M_SECS = 60
def time_string(time):
dd = int(time / D_SECS)
hh = int((time - dd*D_SECS) / H_SECS)
mm = int((time - dd*D_SECS - hh*H_SECS) / M_SECS)
ss = int(time % 60)
return '{0:0>2}:{1:0>2}:{2:0>2}:{3:0>2}'.format(dd, hh, mm, ss)
class ProgressBar(object):
""" """
def __init__(self, title):
self.title = title
self.time_start = -1
self.time_update = -1
self.cur_state = -1
def start(self, initial=None):
self.time_start = time.time()
sys.stdout.write(self.title + ": [" + "-"*BAR_SIZE + "]" +
" time remaining est.: dd:hh:mm:ss")
sys.stdout.flush()
def update(self, new):
if new == 0.0:
time_str = "dd:hh:mm:ss"
elif new == self.cur_state:
adjust = time.time() - self.time_update
time_str = time_string((1-new)*(self.time_update - self.time_start)/new - adjust)
elif new > self.cur_state:
self.time_update = time.time()
time_str = time_string((1-new)*(self.time_update - self.time_start)/new)
self.cur_state = new
new = int(new * BAR_SIZE)
if self.time_start > 0:
sys.stdout.write("\r" + self.title + ": [" + "#"*new + "-"*(BAR_SIZE-new) + "]" +
" time remaining est.: " + time_str)
sys.stdout.flush()
def end(self):
time_str = time_string(time.time() - self.time_start)
if self.time_start > 0:
sys.stdout.write("\r" + self.title + ": [" + "#"*BAR_SIZE + "]" +
" total " + time_str + "\n")
sys.stdout.flush()
class ProgressThread(threading.Thread):
"""Thread which checks the global_status variable and prints a ProgressBar."""
def __init__(self, interval=0.1):
super(ProgressThread, self).__init__()
self.daemon = True
self._stop = threading.Event()
self.interval = interval
self.fraction = 0.0
self.bar = ProgressBar(global_status["text"])
def run(self):
while True:
status_text = global_status["text"]
status_frac = global_status["fraction"]
self.bar.update(status_frac)
if self.bar.title != status_text:
self.bar.end()
self.bar = ProgressBar(status_text)
self.bar.start()
if self.stopped():
self.bar.end()
return
time.sleep(self.interval)
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
# demo
if __name__ == '__main__':
bar = ProgressBar("blabla")
bar.start()
time.sleep(3)
bar.update(0.25)
time.sleep(3)
bar.update(0.5)
time.sleep(3)
bar.update(0.75)
time.sleep(3)
bar.end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment