bar.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2012 Giorgos Verigakis <verigak@gmail.com>
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. from . import Progress
  16. from .helpers import WritelnMixin
  17. class Bar(WritelnMixin, Progress):
  18. width = 32
  19. message = ''
  20. suffix = '%(index)d/%(max)d'
  21. bar_prefix = ' |'
  22. bar_suffix = '| '
  23. empty_fill = ' '
  24. fill = '#'
  25. hide_cursor = True
  26. def update(self):
  27. filled_length = int(self.width * self.progress)
  28. empty_length = self.width - filled_length
  29. message = self.message % self
  30. bar = self.fill * filled_length
  31. empty = self.empty_fill * empty_length
  32. suffix = self.suffix % self
  33. line = ''.join([message, self.bar_prefix, bar, empty, self.bar_suffix,
  34. suffix])
  35. self.writeln(line)
  36. class ChargingBar(Bar):
  37. suffix = '%(percent)d%%'
  38. bar_prefix = ' '
  39. bar_suffix = ' '
  40. empty_fill = u'∙'
  41. fill = u'█'
  42. class FillingSquaresBar(ChargingBar):
  43. empty_fill = u'▢'
  44. fill = u'▣'
  45. class FillingCirclesBar(ChargingBar):
  46. empty_fill = u'◯'
  47. fill = u'◉'
  48. class IncrementalBar(Bar):
  49. phases = (u' ', u'▏', u'▎', u'▍', u'▌', u'▋', u'▊', u'▉', u'█')
  50. def update(self):
  51. nphases = len(self.phases)
  52. expanded_length = int(nphases * self.width * self.progress)
  53. filled_length = int(self.width * self.progress)
  54. empty_length = self.width - filled_length
  55. phase = expanded_length - (filled_length * nphases)
  56. message = self.message % self
  57. bar = self.phases[-1] * filled_length
  58. current = self.phases[phase] if phase > 0 else ''
  59. empty = self.empty_fill * max(0, empty_length - len(current))
  60. suffix = self.suffix % self
  61. line = ''.join([message, self.bar_prefix, bar, current, empty,
  62. self.bar_suffix, suffix])
  63. self.writeln(line)
  64. class ShadyBar(IncrementalBar):
  65. phases = (u' ', u'░', u'▒', u'▓', u'█')