Created
March 11, 2015 01:15
-
-
Save rogerhub/2d257b75cbd0087b82c1 to your computer and use it in GitHub Desktop.
Simple progress report for batch jobs Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import threading | |
import sys | |
class ProgressReport(object): | |
interval = 0.2 | |
def __init__(self, name, fn): | |
self.job_name = name | |
self.fn = fn | |
self.stopped = False | |
self.runLock = threading.Lock() | |
self._report() | |
self.loop_thread = threading.Timer(self.interval, self._loop, []) | |
self.loop_thread.daemon = True | |
self.loop_thread.start() | |
def _report(self): | |
progress = self.fn() | |
if type(progress) is int: | |
sys.stdout.write("\r%s... %d" % (self.job_name, progress)) | |
elif type(progress) is float: | |
sys.stdout.write("\r%s... %f" % (self.job_name, progress)) | |
else: | |
sys.stdout.write("\r%s... %s" % (self.job_name, str(progress))) | |
sys.stdout.flush() | |
def _loop(self): | |
while True: | |
self.runLock.acquire() | |
if self.fn is None: | |
continue | |
if self.stopped: | |
self.runLock.release() | |
break | |
self._report() | |
self.runLock.release() | |
time.sleep(self.interval) | |
def end(self): | |
self.runLock.acquire() | |
self.stopped = True | |
sys.stdout.write("\r%s... done\n" % (self.job_name)) | |
sys.stdout.flush() | |
self.runLock.release() | |
if __name__ == '__main__': | |
import random | |
i = 0 | |
def progress(): | |
return "%d%%" % (i,) | |
pr = ProgressReport("Sleeping", progress) | |
for _ in range(100): | |
time.sleep(random.random() * 0.1) | |
i += 1 | |
pr.end() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment