progressbar.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # -*- coding: utf-8 -*-
  2. #
  3. # progressbar - Text progress bar library for Python.
  4. # Copyright (c) 2005 Nilton Volpato
  5. #
  6. # (With some small changes after importing into BitBake)
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  21. """Main ProgressBar class."""
  22. from __future__ import division
  23. import math
  24. import os
  25. import signal
  26. import sys
  27. import time
  28. try:
  29. from fcntl import ioctl
  30. from array import array
  31. import termios
  32. except ImportError:
  33. pass
  34. from .compat import * # for: any, next
  35. from . import widgets
  36. class UnknownLength: pass
  37. class ProgressBar(object):
  38. """The ProgressBar class which updates and prints the bar.
  39. A common way of using it is like:
  40. >>> pbar = ProgressBar().start()
  41. >>> for i in range(100):
  42. ... # do something
  43. ... pbar.update(i+1)
  44. ...
  45. >>> pbar.finish()
  46. You can also use a ProgressBar as an iterator:
  47. >>> progress = ProgressBar()
  48. >>> for i in progress(some_iterable):
  49. ... # do something
  50. ...
  51. Since the progress bar is incredibly customizable you can specify
  52. different widgets of any type in any order. You can even write your own
  53. widgets! However, since there are already a good number of widgets you
  54. should probably play around with them before moving on to create your own
  55. widgets.
  56. The term_width parameter represents the current terminal width. If the
  57. parameter is set to an integer then the progress bar will use that,
  58. otherwise it will attempt to determine the terminal width falling back to
  59. 80 columns if the width cannot be determined.
  60. When implementing a widget's update method you are passed a reference to
  61. the current progress bar. As a result, you have access to the
  62. ProgressBar's methods and attributes. Although there is nothing preventing
  63. you from changing the ProgressBar you should treat it as read only.
  64. Useful methods and attributes include (Public API):
  65. - currval: current progress (0 <= currval <= maxval)
  66. - maxval: maximum (and final) value
  67. - finished: True if the bar has finished (reached 100%)
  68. - start_time: the time when start() method of ProgressBar was called
  69. - seconds_elapsed: seconds elapsed since start_time and last call to
  70. update
  71. - percentage(): progress in percent [0..100]
  72. """
  73. __slots__ = ('currval', 'fd', 'finished', 'last_update_time',
  74. 'left_justify', 'maxval', 'next_update', 'num_intervals',
  75. 'poll', 'seconds_elapsed', 'signal_set', 'start_time',
  76. 'term_width', 'update_interval', 'widgets', '_time_sensitive',
  77. '__iterable')
  78. _DEFAULT_MAXVAL = 100
  79. _DEFAULT_TERMSIZE = 80
  80. _DEFAULT_WIDGETS = [widgets.Percentage(), ' ', widgets.Bar()]
  81. def __init__(self, maxval=None, widgets=None, term_width=None, poll=1,
  82. left_justify=True, fd=sys.stderr):
  83. """Initializes a progress bar with sane defaults."""
  84. # Don't share a reference with any other progress bars
  85. if widgets is None:
  86. widgets = list(self._DEFAULT_WIDGETS)
  87. self.maxval = maxval
  88. self.widgets = widgets
  89. self.fd = fd
  90. self.left_justify = left_justify
  91. self.signal_set = False
  92. if term_width is not None:
  93. self.term_width = term_width
  94. else:
  95. try:
  96. self._handle_resize(None, None)
  97. signal.signal(signal.SIGWINCH, self._handle_resize)
  98. self.signal_set = True
  99. except (SystemExit, KeyboardInterrupt): raise
  100. except Exception as e:
  101. print("DEBUG 5 %s" % e)
  102. self.term_width = self._env_size()
  103. self.__iterable = None
  104. self._update_widgets()
  105. self.currval = 0
  106. self.finished = False
  107. self.last_update_time = None
  108. self.poll = poll
  109. self.seconds_elapsed = 0
  110. self.start_time = None
  111. self.update_interval = 1
  112. self.next_update = 0
  113. def __call__(self, iterable):
  114. """Use a ProgressBar to iterate through an iterable."""
  115. try:
  116. self.maxval = len(iterable)
  117. except:
  118. if self.maxval is None:
  119. self.maxval = UnknownLength
  120. self.__iterable = iter(iterable)
  121. return self
  122. def __iter__(self):
  123. return self
  124. def __next__(self):
  125. try:
  126. value = next(self.__iterable)
  127. if self.start_time is None:
  128. self.start()
  129. else:
  130. self.update(self.currval + 1)
  131. return value
  132. except StopIteration:
  133. if self.start_time is None:
  134. self.start()
  135. self.finish()
  136. raise
  137. # Create an alias so that Python 2.x won't complain about not being
  138. # an iterator.
  139. next = __next__
  140. def _env_size(self):
  141. """Tries to find the term_width from the environment."""
  142. return int(os.environ.get('COLUMNS', self._DEFAULT_TERMSIZE)) - 1
  143. def _handle_resize(self, signum=None, frame=None):
  144. """Tries to catch resize signals sent from the terminal."""
  145. h, w = array('h', ioctl(self.fd, termios.TIOCGWINSZ, '\0' * 8))[:2]
  146. self.term_width = w
  147. def percentage(self):
  148. """Returns the progress as a percentage."""
  149. if self.currval >= self.maxval:
  150. return 100.0
  151. return (self.currval * 100.0 / self.maxval) if self.maxval else 100.00
  152. percent = property(percentage)
  153. def _format_widgets(self):
  154. result = []
  155. expanding = []
  156. width = self.term_width
  157. for index, widget in enumerate(self.widgets):
  158. if isinstance(widget, widgets.WidgetHFill):
  159. result.append(widget)
  160. expanding.insert(0, index)
  161. else:
  162. widget = widgets.format_updatable(widget, self)
  163. result.append(widget)
  164. width -= len(widget)
  165. count = len(expanding)
  166. while count:
  167. portion = max(int(math.ceil(width * 1. / count)), 0)
  168. index = expanding.pop()
  169. count -= 1
  170. widget = result[index].update(self, portion)
  171. width -= len(widget)
  172. result[index] = widget
  173. return result
  174. def _format_line(self):
  175. """Joins the widgets and justifies the line."""
  176. widgets = ''.join(self._format_widgets())
  177. if self.left_justify: return widgets.ljust(self.term_width)
  178. else: return widgets.rjust(self.term_width)
  179. def _need_update(self):
  180. """Returns whether the ProgressBar should redraw the line."""
  181. if self.currval >= self.next_update or self.finished: return True
  182. delta = time.time() - self.last_update_time
  183. return self._time_sensitive and delta > self.poll
  184. def _update_widgets(self):
  185. """Checks all widgets for the time sensitive bit."""
  186. self._time_sensitive = any(getattr(w, 'TIME_SENSITIVE', False)
  187. for w in self.widgets)
  188. def update(self, value=None):
  189. """Updates the ProgressBar to a new value."""
  190. if value is not None and value is not UnknownLength:
  191. if (self.maxval is not UnknownLength
  192. and not 0 <= value <= self.maxval):
  193. raise ValueError('Value out of range')
  194. self.currval = value
  195. if not self._need_update(): return
  196. if self.start_time is None:
  197. raise RuntimeError('You must call "start" before calling "update"')
  198. now = time.time()
  199. self.seconds_elapsed = now - self.start_time
  200. self.next_update = self.currval + self.update_interval
  201. output = self._format_line()
  202. self.fd.write(output + '\r')
  203. self.fd.flush()
  204. self.last_update_time = now
  205. return output
  206. def start(self, update=True):
  207. """Starts measuring time, and prints the bar at 0%.
  208. It returns self so you can use it like this:
  209. >>> pbar = ProgressBar().start()
  210. >>> for i in range(100):
  211. ... # do something
  212. ... pbar.update(i+1)
  213. ...
  214. >>> pbar.finish()
  215. """
  216. if self.maxval is None:
  217. self.maxval = self._DEFAULT_MAXVAL
  218. self.num_intervals = max(100, self.term_width)
  219. self.next_update = 0
  220. if self.maxval is not UnknownLength:
  221. if self.maxval < 0: raise ValueError('Value out of range')
  222. self.update_interval = self.maxval / self.num_intervals
  223. self.start_time = time.time()
  224. if update:
  225. self.last_update_time = self.start_time
  226. self.update(0)
  227. else:
  228. self.last_update_time = 0
  229. return self
  230. def finish(self):
  231. """Puts the ProgressBar bar in the finished state."""
  232. if self.finished:
  233. return
  234. self.finished = True
  235. self.update(self.maxval)
  236. self.fd.write('\n')
  237. if self.signal_set:
  238. signal.signal(signal.SIGWINCH, signal.SIG_DFL)