4grab/progressbar.py
2010-02-12 00:18:34 +01:00

63 lines
2.3 KiB
Python

######################################################################
# Copyright 2009, 2010 ryuslash
#
# This file is part of 4grab.
#
# 4grab is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 4grab is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with 4grab. If not, see <http://www.gnu.org/licenses/>.
######################################################################
import sys
import time
class Progress():
def __init__(self, maxvalue, maxwidth=79, fd=sys.stdout):
self.maxwidth = maxwidth
self.maxvalue = maxvalue
self.fd = fd
self.prog_char = '#'
self.fill_char = ' '
self.show_progress(0)
def __get_true_maxwidth(self, vallen, maxvallen):
return self.maxwidth - 4 - vallen - maxvallen
def show_progress(self, value):
str_value = str(value)
str_maxvalue = str(self.maxvalue)
true_maxwidth = self.__get_true_maxwidth(len(str_value), len(str_maxvalue))
if self.maxvalue == 0:
progress = true_maxwidth
else:
progress = int(round((true_maxwidth/float(self.maxvalue))*value))
self.__write_progress(str_value, str_maxvalue, progress, true_maxwidth)
def __write_progress(self, str_value, str_maxvalue, progress, true_maxwidth):
self.fd.write("\r%s/%s [%s%s]" % (str_value, str_maxvalue, self.prog_char * progress, self.fill_char * (true_maxwidth - progress)))
self.fd.flush()
def complete(self):
str_maxvalue = str(self.maxvalue)
vallen = len(str_maxvalue)
true_maxwidth = self.__get_true_maxwidth(vallen, vallen)
self.__write_progress(str_maxvalue, str_maxvalue, true_maxwidth, true_maxwidth)
self.fd.write("\n")
if __name__ == "__main__":
prog = Progress(200)
for i in range(1, 201):
prog.show_progress(i)
time.sleep(0.1)