Coverage for python/lsst/resources/packageresource.py: 100%
23 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-03-31 02:36 -0700
« prev ^ index » next coverage.py v6.5.0, created at 2023-03-31 02:36 -0700
1# This file is part of lsst-resources.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# Use of this source code is governed by a 3-clause BSD-style
10# license that can be found in the LICENSE file.
12import contextlib
13import logging
14from typing import Iterator, Optional
16import pkg_resources
18__all__ = ("PackageResourcePath",)
20from ._resourceHandles._baseResourceHandle import ResourceHandleProtocol
21from ._resourcePath import ResourcePath
23log = logging.getLogger(__name__)
26class PackageResourcePath(ResourcePath):
27 """URI referring to a Python package resource.
29 These URIs look like: ``resource://lsst.daf.butler/configs/file.yaml``
30 where the network location is the Python package and the path is the
31 resource name.
32 """
34 def exists(self) -> bool:
35 """Check that the python resource exists."""
36 return pkg_resources.resource_exists(self.netloc, self.relativeToPathRoot)
38 def read(self, size: int = -1) -> bytes:
39 """Read the contents of the resource."""
40 with pkg_resources.resource_stream(self.netloc, self.relativeToPathRoot) as fh:
41 return fh.read(size)
43 @contextlib.contextmanager
44 def open(
45 self,
46 mode: str = "r",
47 *,
48 encoding: Optional[str] = None,
49 prefer_file_temporary: bool = False,
50 ) -> Iterator[ResourceHandleProtocol]:
51 # Docstring inherited.
52 if "r" not in mode or "+" in mode:
53 raise RuntimeError(f"Package resource URI {self} is read-only.")
54 if "b" in mode:
55 with pkg_resources.resource_stream(self.netloc, self.relativeToPathRoot) as buffer:
56 yield buffer
57 else:
58 with super().open(mode, encoding=encoding, prefer_file_temporary=prefer_file_temporary) as buffer:
59 yield buffer