program_public_tools.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import os
  2. import socket
  3. from typing import Any, Optional
  4. import time
  5. class Timer:
  6. def __init__(self):
  7. self.start_time = None
  8. def start(self):
  9. if self.start_time is not None:
  10. print("Timer is already running. Use .elapsed_time() to check the time elapsed.")
  11. else:
  12. self.start_time = time.time()
  13. def elapsed_time(self):
  14. if self.start_time is None:
  15. print("Timer has not started yet. Use .start() to start the timer.")
  16. else:
  17. return time.time() - self.start_time
  18. def reset(self):
  19. self.start_time = None
  20. class ProgramPublicTools(object):
  21. def __init__(self, enable_terminal_debug_output: bool = True):
  22. self.enable_terminal_debug_output = enable_terminal_debug_output
  23. def debug_output(self, *message: Any) -> None:
  24. self.__terminal_debug_output(*message)
  25. def __terminal_debug_output(self, *message: Any) -> None:
  26. if self.enable_terminal_debug_output is True:
  27. print(*message)
  28. @staticmethod
  29. def path_directory_exist_check(full_path: str) -> None:
  30. folder_path = os.path.dirname(full_path)
  31. os.makedirs(folder_path, exist_ok=True)
  32. @staticmethod
  33. def get_absolute_path(relative_path: str) -> str:
  34. script_dir = os.path.dirname(os.path.realpath(__file__))
  35. return os.path.abspath(os.path.join(script_dir, relative_path))
  36. @staticmethod
  37. def create_timer() -> Timer:
  38. return Timer()
  39. @staticmethod
  40. def is_convertible_to_int(num) -> tuple[bool, Optional[int]]:
  41. try:
  42. s = num
  43. s = int(s)
  44. return True, s
  45. except ValueError:
  46. return False, None
  47. @staticmethod
  48. def is_convertible_to_float(num) -> tuple[bool, Optional[float]]:
  49. try:
  50. s = num
  51. s = float(s)
  52. return True, s
  53. except ValueError:
  54. return False, None
  55. @staticmethod
  56. def find_available_server_port(number: int = 1, not_list: list[int] = None, address: str = "localhost",
  57. start_port: int = 1024, end_port: int = 65535) -> list[int]:
  58. get_port = []
  59. for port in range(start_port, end_port + 1):
  60. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  61. try:
  62. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 0)
  63. sock.bind((address, port))
  64. if not_list is not None:
  65. if port in not_list:
  66. pass
  67. else:
  68. get_port.append(port)
  69. else:
  70. get_port.append(port)
  71. if len(get_port) == number:
  72. break
  73. except OSError:
  74. continue
  75. finally:
  76. sock.close()
  77. if len(get_port) < number:
  78. raise Exception("Error: Do not find enough available port.")
  79. else:
  80. return get_port