progress.py 2.0 KB

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