|
2 | 2 |
|
3 | 3 | # stdlib
|
4 | 4 | import sys
|
| 5 | +from typing import TextIO |
5 | 6 |
|
6 | 7 | if sys.version_info[:2] < (3, 7): # pragma: no cover (py37+)
|
7 | 8 | # 3rd party
|
8 | 9 | import importlib_resources
|
| 10 | + from importlib_resources._common import normalize_path |
| 11 | + |
9 | 12 | globals().update(importlib_resources.__dict__)
|
| 13 | + |
| 14 | + def read_binary(package: importlib_resources.Package, resource: importlib_resources.Resource) -> bytes: |
| 15 | + """ |
| 16 | + Return the binary contents of the resource. |
| 17 | + """ |
| 18 | + |
| 19 | + return (importlib_resources.files(package) / normalize_path(resource)).read_bytes() |
| 20 | + |
| 21 | + def open_text( |
| 22 | + package: importlib_resources.Package, |
| 23 | + resource: importlib_resources.Resource, |
| 24 | + encoding: str = 'utf-8', |
| 25 | + errors: str = 'strict', |
| 26 | + ) -> TextIO: |
| 27 | + """ |
| 28 | + Return a file-like object opened for text reading of the resource. |
| 29 | + """ |
| 30 | + |
| 31 | + return (importlib_resources.files(package) / normalize_path(resource)).open( |
| 32 | + 'r', |
| 33 | + encoding=encoding, |
| 34 | + errors=errors, |
| 35 | + ) |
| 36 | + |
| 37 | + def read_text( |
| 38 | + package: importlib_resources.Package, |
| 39 | + resource: importlib_resources.Resource, |
| 40 | + encoding: str = 'utf-8', |
| 41 | + errors: str = 'strict', |
| 42 | + ) -> str: |
| 43 | + """ |
| 44 | + Return the decoded string of the resource. |
| 45 | + """ |
| 46 | + |
| 47 | + with importlib_resources.open_text(package, resource, encoding, errors) as fp: |
| 48 | + return fp.read() |
| 49 | + |
10 | 50 | else: # pragma: no cover (<py39)
|
11 | 51 | # stdlib
|
12 | 52 | import importlib.resources
|
|
0 commit comments