progress.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #
  2. # Copyright (C) 2009 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import sys
  17. from time import time
  18. from trace import IsTrace
  19. _NOT_TTY = not os.isatty(2)
  20. class Progress(object):
  21. def __init__(self, title, total=0, units='', print_newline=False,
  22. always_print_percentage=False):
  23. self._title = title
  24. self._total = total
  25. self._done = 0
  26. self._lastp = -1
  27. self._start = time()
  28. self._show = False
  29. self._units = units
  30. self._print_newline = print_newline
  31. self._always_print_percentage = always_print_percentage
  32. def update(self, inc=1):
  33. self._done += inc
  34. if _NOT_TTY or IsTrace():
  35. return
  36. if not self._show:
  37. if 0.5 <= time() - self._start:
  38. self._show = True
  39. else:
  40. return
  41. if self._total <= 0:
  42. sys.stderr.write('\r%s: %d, ' % (
  43. self._title,
  44. self._done))
  45. sys.stderr.flush()
  46. else:
  47. p = (100 * self._done) / self._total
  48. if self._lastp != p or self._always_print_percentage:
  49. self._lastp = p
  50. sys.stderr.write('\r%s: %3d%% (%d%s/%d%s)%s' % (
  51. self._title,
  52. p,
  53. self._done, self._units,
  54. self._total, self._units,
  55. "\n" if self._print_newline else ""))
  56. sys.stderr.flush()
  57. def end(self):
  58. if _NOT_TTY or IsTrace() or not self._show:
  59. return
  60. if self._total <= 0:
  61. sys.stderr.write('\r%s: %d, done. \n' % (
  62. self._title,
  63. self._done))
  64. sys.stderr.flush()
  65. else:
  66. p = (100 * self._done) / self._total
  67. sys.stderr.write('\r%s: %3d%% (%d%s/%d%s), done. \n' % (
  68. self._title,
  69. p,
  70. self._done, self._units,
  71. self._total, self._units))
  72. sys.stderr.flush()