yaml_utils.py 1.1 KB

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