progressbar.py 9.6 KB

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