yaml_utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import logging
  2. import os
  3. import yaml
  4. from yaml import YAMLError
  5. logger = logging.getLogger(__name__)
  6. def load_yaml_file(file_path: str, ignore_error: bool = False) -> dict:
  7. """
  8. Safe loading a YAML file to a dict
  9. :param file_path: the path of the YAML file
  10. :param ignore_error:
  11. if True, return empty dict if error occurs and the error will be logged in warning level
  12. if False, raise error if error occurs
  13. :return: a dict of the YAML content
  14. """
  15. try:
  16. if not file_path or not os.path.exists(file_path):
  17. raise FileNotFoundError(f'Failed to load YAML file {file_path}: file not found')
  18. with open(file_path, encoding='utf-8') as file:
  19. try:
  20. return yaml.safe_load(file)
  21. except Exception as e:
  22. raise YAMLError(f'Failed to load YAML file {file_path}: {e}')
  23. except FileNotFoundError as e:
  24. logger.debug(f'Failed to load YAML file {file_path}: {e}')
  25. return {}
  26. except Exception as e:
  27. if ignore_error:
  28. logger.warning(f'Failed to load YAML file {file_path}: {e}')
  29. return {}
  30. else:
  31. raise e