lib.py 3.2 KB

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