progress.py 1.9 KB

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