lib.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import os
  2. import sys
  3. import locale
  4. import random
  5. import time
  6. import signal
  7. from contextlib import contextmanager
  8. @contextmanager
  9. def default_sigint():
  10. original_sigint_handler = signal.getsignal(signal.SIGINT)
  11. signal.signal(signal.SIGINT, signal.SIG_DFL)
  12. try:
  13. yield
  14. finally:
  15. signal.signal(signal.SIGINT, original_sigint_handler)
  16. def to_utf8(s):
  17. """Re-encode string from the default system encoding to UTF-8."""
  18. current = locale.getpreferredencoding()
  19. if hasattr(s, 'decode'):
  20. return s.decode(current).encode("UTF-8") if s and current != "UTF-8" else s
  21. else:
  22. return bytes.decode(s)
  23. def debug(obj, fd=sys.stderr):
  24. """Write obj to standard error."""
  25. try:
  26. unicode
  27. except NameError:
  28. unicode = bytes
  29. string = str(obj.encode(get_encoding(fd), "backslashreplace")
  30. if isinstance(obj, unicode) else obj)
  31. fd.write(string + "\n")
  32. def catch_exceptions(exit_codes, fun, *args, **kwargs):
  33. """
  34. Catch exceptions on fun(*args, **kwargs) and return the exit code specified
  35. in the exit_codes dictionary. Return 0 if no exception is raised.
  36. """
  37. try:
  38. fun(*args, **kwargs)
  39. return 0
  40. except tuple(exit_codes.keys()) as exc:
  41. debug("[%s] %s" % (exc.__class__.__name__, exc))
  42. return exit_codes[exc.__class__]
  43. def get_encoding(fd):
  44. """Guess terminal encoding."""
  45. return fd.encoding or locale.getpreferredencoding()
  46. def first(it):
  47. """Return first element in iterable."""
  48. return it.next()
  49. def string_to_dict(string):
  50. """Return dictionary from string "key1=value1, key2=value2"."""
  51. if string:
  52. pairs = [s.strip() for s in string.split(",")]
  53. return dict(pair.split("=") for pair in pairs)
  54. def get_first_existing_filename(prefixes, relative_path):
  55. """Get the first existing filename of relative_path seeking on prefixes directories."""
  56. for prefix in prefixes:
  57. path = os.path.join(prefix, relative_path)
  58. if os.path.exists(path):
  59. return path
  60. def retriable_exceptions(fun, retriable_exceptions, max_retries=None):
  61. """Run function and retry on some exceptions (with exponential backoff)."""
  62. retry = 0
  63. while 1:
  64. try:
  65. return fun()
  66. except tuple(retriable_exceptions) as exc:
  67. retry += 1
  68. if type(exc) not in retriable_exceptions:
  69. raise exc
  70. elif max_retries is not None and retry > max_retries:
  71. debug("[Retryable errors] Retry limit reached")
  72. raise exc
  73. else:
  74. seconds = random.uniform(0, 2**retry)
  75. message = ("[Retryable error {current_retry}/{total_retries}] " +
  76. "{error_type} ({error_msg}). Wait {wait_time} seconds").format(
  77. current_retry=retry,
  78. total_retries=max_retries or "-",
  79. error_type=type(exc).__name__,
  80. error_msg=str(exc) or "-",
  81. wait_time="%.1f" % seconds,
  82. )
  83. debug(message)
  84. time.sleep(seconds)