diff --git a/glad/files/__init__.py b/glad/files/__init__.py index 90ed017a..fe6216f9 100644 --- a/glad/files/__init__.py +++ b/glad/files/__init__.py @@ -8,13 +8,19 @@ from urllib.parse import urlparse try: - from pkg_resources import resource_exists, resource_stream + from importlib.resources import files + + def resource_open(package, name, *args, **kwargs): + return files(package).joinpath(name).open(*args, **kwargs) except ImportError: - def resource_exists(*args, **kwargs): - return False + try: + from pkg_resources import resource_stream - def resource_stream(*args, **kwargs): - return None + def resource_open(package, name, *args, **kwargs): + return resource_stream(package, name) + except ImportError: + def resource_open(package, name, *args, **kwargs): + raise FileNotFoundError BASE_PATH = os.path.abspath(os.path.dirname(__file__)) @@ -29,12 +35,13 @@ class GladFileException(Exception): def open_local(name, *args, **kwargs): # use pkg_resources when available, makes it work in zipped modules # or other environments - if resource_exists(__name__, name): - logger.info('opening packaged resource: %r', name) - return resource_stream(__name__, name) + try: + return resource_open(__name__, name, *args, **kwargs) + except FileNotFoundError: + pass # fallback to filesystem - logger.info('opening packaged path: %r', name) + logger.info('falling back to packaged path: %r', name) local_path = os.path.normpath(os.path.join(BASE_PATH, os.path.join(name))) if not local_path.startswith(BASE_PATH): raise GladFileException('unsafe file path, won\'t open {!r}'.format(local_path))