progress.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. self._title = title
  23. self._total = total
  24. self._done = 0
  25. self._lastp = -1
  26. self._start = time()
  27. self._show = False
  28. self._units = units
  29. self._print_newline = print_newline
  30. def update(self, inc=1):
  31. self._done += inc
  32. if _NOT_TTY or IsTrace():
  33. return
  34. if not self._show:
  35. if 0.5 <= time() - self._start:
  36. self._show = True
  37. else:
  38. return
  39. if self._total <= 0:
  40. sys.stderr.write('\r%s: %d, ' % (
  41. self._title,
  42. self._done))
  43. sys.stderr.flush()
  44. else:
  45. p = (100 * self._done) / self._total
  46. if self._lastp != p:
  47. self._lastp = p
  48. sys.stderr.write('\r%s: %3d%% (%d%s/%d%s)%s' % (
  49. self._title,
  50. p,
  51. self._done, self._units,
  52. self._total, self._units,
  53. "\n" if self._print_newline else ""))
  54. sys.stderr.flush()
  55. def end(self):
  56. if _NOT_TTY or IsTrace() or not self._show:
  57. return
  58. if self._total <= 0:
  59. sys.stderr.write('\r%s: %d, done. \n' % (
  60. self._title,
  61. self._done))
  62. sys.stderr.flush()
  63. else:
  64. p = (100 * self._done) / self._total
  65. sys.stderr.write('\r%s: %3d%% (%d%s/%d%s), done. \n' % (
  66. self._title,
  67. p,
  68. self._done, self._units,
  69. self._total, self._units))
  70. sys.stderr.flush()