progress.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 repo_trace import IsTrace
  20. _NOT_TTY = not os.isatty(2)
  21. # This will erase all content in the current line (wherever the cursor is).
  22. # It does not move the cursor, so this is usually followed by \r to move to
  23. # column 0.
  24. CSI_ERASE_LINE = '\x1b[2K'
  25. class Progress(object):
  26. def __init__(self, title, total=0, units='', print_newline=False,
  27. always_print_percentage=False):
  28. self._title = title
  29. self._total = total
  30. self._done = 0
  31. self._lastp = -1
  32. self._start = time()
  33. self._show = False
  34. self._units = units
  35. self._print_newline = print_newline
  36. self._always_print_percentage = always_print_percentage
  37. def update(self, inc=1, msg=''):
  38. self._done += inc
  39. if _NOT_TTY or IsTrace():
  40. return
  41. if not self._show:
  42. if 0.5 <= time() - self._start:
  43. self._show = True
  44. else:
  45. return
  46. if self._total <= 0:
  47. sys.stderr.write('%s\r%s: %d,' % (
  48. CSI_ERASE_LINE,
  49. self._title,
  50. self._done))
  51. sys.stderr.flush()
  52. else:
  53. p = (100 * self._done) / self._total
  54. if self._lastp != p or self._always_print_percentage:
  55. self._lastp = p
  56. sys.stderr.write('%s\r%s: %3d%% (%d%s/%d%s)%s%s%s' % (
  57. CSI_ERASE_LINE,
  58. self._title,
  59. p,
  60. self._done, self._units,
  61. self._total, self._units,
  62. ' ' if msg else '', msg,
  63. "\n" if self._print_newline else ""))
  64. sys.stderr.flush()
  65. def end(self):
  66. if _NOT_TTY or IsTrace() or not self._show:
  67. return
  68. if self._total <= 0:
  69. sys.stderr.write('%s\r%s: %d, done.\n' % (
  70. CSI_ERASE_LINE,
  71. self._title,
  72. self._done))
  73. sys.stderr.flush()
  74. else:
  75. p = (100 * self._done) / self._total
  76. sys.stderr.write('%s\r%s: %3d%% (%d%s/%d%s), done.\n' % (
  77. CSI_ERASE_LINE,
  78. self._title,
  79. p,
  80. self._done, self._units,
  81. self._total, self._units))
  82. sys.stderr.flush()