progress.py 2.3 KB

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