From 751c25c3684b8e634c9b804f384950fa4c6d1768 Mon Sep 17 00:00:00 2001 From: Simon Cross Date: Sat, 17 May 2014 16:47:10 +0200 Subject: [PATCH] Add direct yaml and json support to resources. --- naja/resources/__init__.py | 4 +++- naja/resources/loader.py | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/naja/resources/__init__.py b/naja/resources/__init__.py index 191cbd4..b080786 100644 --- a/naja/resources/__init__.py +++ b/naja/resources/__init__.py @@ -1,3 +1,5 @@ -from naja.resources.loader import Loader +from naja.resources.loader import Loader, ResourceNotFound + +__all__ = ['resources', 'ResourceNotFound'] resources = Loader('data') diff --git a/naja/resources/loader.py b/naja/resources/loader.py index 28a3c7a..69eff2f 100644 --- a/naja/resources/loader.py +++ b/naja/resources/loader.py @@ -1,5 +1,6 @@ import os import sys +import json try: from pkg_resources import resource_filename @@ -11,6 +12,12 @@ except ImportError: # time going down this rabbithole already return os.path.join(os.path.dirname(__file__), '..', '..', 'data', path) + +try: + import yaml +except ImportError: + yaml = None + import pygame @@ -99,3 +106,15 @@ class Loader(object): self._cache[key] = pygame.font.Font(fn, font_size) return self._cache[key] + + def get_yaml(self, *path_fragments): + if yaml is None: + raise ResourceNotFound("%s - %s" % ( + os.path.join(*path_fragments), + "YAML module not available")) + with self.get_file(*path_fragments) as yaml_file: + return yaml.safe_load(yaml_file) + + def get_json(self, *path_fragments): + with self.get_file(*path_fragments) as json_file: + return json.load(json_file) -- 2.34.1