utils_others.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import time
  2. import socket
  3. import logging
  4. def print_with_no(obj):
  5. if hasattr(obj, '__len__'):
  6. for k, item in enumerate(obj):
  7. print('[{}/{}] {}'.format(k+1, len(obj), item))
  8. elif hasattr(obj, '__iter__'):
  9. for k, item in enumerate(obj):
  10. print('[{}] {}'.format(k+1, item))
  11. else:
  12. print('[1] {}'.format(obj))
  13. def get_file_line_count(filename):
  14. line_count = 0
  15. buffer_size = 1024 * 1024 * 8
  16. with open(filename, 'r') as f:
  17. while True:
  18. data = f.read(buffer_size)
  19. if not data:
  20. break
  21. line_count += data.count('\n')
  22. return line_count
  23. def get_host_ip():
  24. try:
  25. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  26. s.connect(('8.8.8.8', 80))
  27. ip = s.getsockname()[0]
  28. finally:
  29. s.close()
  30. return ip
  31. class ContextTimer(object):
  32. """
  33. References:
  34. WithTimer in https://github.com/uber/ludwig/blob/master/ludwig/utils/time_utils.py
  35. """
  36. def __init__(self, name=None, use_log=False, quiet=False):
  37. self.use_log = use_log
  38. self.quiet = quiet
  39. if name is None:
  40. self.name = ''
  41. else:
  42. self.name = '{}, '.format(name.rstrip())
  43. def __enter__(self):
  44. self.start_time = time.time()
  45. if not self.quiet:
  46. self._print_or_log('{}{} starts'.format(self.name, self._now_time_str))
  47. return self
  48. def __exit__(self, exc_type, exc_val, exc_tb):
  49. if not self.quiet:
  50. self._print_or_log('{}elapsed_time = {:.5}s'.format(self.name, self.get_eplased_time()))
  51. self._print_or_log('{}{} ends'.format(self.name, self._now_time_str))
  52. @property
  53. def _now_time_str(self):
  54. return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  55. def _print_or_log(self, output_str):
  56. if self.use_log:
  57. logging.info(output_str)
  58. else:
  59. print(output_str)
  60. def get_eplased_time(self):
  61. return time.time() - self.start_time
  62. def enter(self):
  63. """Manually trigger enter"""
  64. self.__enter__()
  65. def set_logger(filename, level=logging.INFO, logger_name=None):
  66. logger = logging.getLogger(logger_name)
  67. logger.setLevel(level)
  68. # Never mutate (insert/remove elements) the list you're currently iterating on.
  69. # If you need, make a copy.
  70. for handler in logger.handlers[:]:
  71. if isinstance(handler, logging.FileHandler):
  72. logger.removeHandler(handler)
  73. # FileHandler is subclass of StreamHandler, so isinstance(handler,
  74. # logging.StreamHandler) is True even if handler is FileHandler.
  75. # if (type(handler) == logging.StreamHandler) and (handler.stream == sys.stderr):
  76. elif type(handler) == logging.StreamHandler:
  77. logger.removeHandler(handler)
  78. file_handler = logging.FileHandler(filename)
  79. file_handler.setFormatter(logging.Formatter('%(message)s'))
  80. logger.addHandler(file_handler)
  81. console_handler = logging.StreamHandler()
  82. console_handler.setFormatter(logging.Formatter('%(message)s'))
  83. logger.addHandler(console_handler)
  84. return logger