__init__.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import io
  2. import pkgutil
  3. from contextlib import contextmanager
  4. __all__ = 'read_binary read_text open_binary open_text is_resource contents path'.split()
  5. try:
  6. FileNotFoundError
  7. except NameError:
  8. FileNotFoundError = OSError
  9. def read_binary(package, resource):
  10. data = pkgutil.get_data(package, resource)
  11. if data is None:
  12. raise FileNotFoundError('{} does not contain {!r}'.format(package, resource))
  13. return data
  14. def read_text(package, resource, encoding='utf-8', errors='strict'):
  15. return read_binary(package, resource).decode(encoding, errors)
  16. def open_binary(package, resource):
  17. return io.BytesIO(read_binary(package, resource))
  18. def open_text(package, resource, encoding='utf-8', errors='strict'):
  19. return io.StringIO(read_text(package, resource, encoding, errors))
  20. def is_resource(package, name):
  21. try:
  22. read_binary(package, name)
  23. return True
  24. except (FileNotFoundError, OSError, IOError):
  25. return False
  26. def contents(package):
  27. raise NotImplementedError('importlib_resources.contents is not implemented')
  28. @contextmanager
  29. def path(package, resource):
  30. raise NotImplementedError('importlib_resources.path is not implemented')
  31. yield None