file_handler.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import pathlib
  2. import os
  3. from .handler import handler
  4. class file_handler(handler):
  5. """
  6. That handler puts log to file given when object was created.
  7. """
  8. def __init__(self, target: pathlib.Path) -> None:
  9. """
  10. That initialize new object with given file.
  11. Parameters
  12. ----------
  13. target : pathlib.Path
  14. File to use by handler.
  15. """
  16. super().__init__()
  17. self.__target = target
  18. self.__handler = None
  19. def add(self, content: str) -> None:
  20. """
  21. That add new content to the file as new line.
  22. Parameters
  23. ----------
  24. content : str
  25. Content to add into the file as new line.
  26. """
  27. if not self.is_ready:
  28. self.open()
  29. self.__handler.write(content + os.linesep)
  30. @property
  31. def is_ready(self) -> bool:
  32. """
  33. That check that file handler is ready to use or not.
  34. """
  35. return self.__handler is not None and not self.__handler.closed
  36. def open(self) -> None:
  37. """
  38. That open file and save handler to use in the future.
  39. """
  40. if not self.is_ready:
  41. self.__handler = self.__target.open("a")
  42. def clean(self) -> None:
  43. """
  44. That close file handler if it is open yet.
  45. """
  46. if not self.is_ready:
  47. return
  48. self.__handler.close()