Created
March 13, 2019 22:33
-
-
Save AstraLuma/166fcf90c9a6b2ab695dd39d38b0bb6f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import collections.abc | |
| import pathlib | |
| __all__ = ('root',) | |
| class AttrsView(collections.abc.KeysView): | |
| def __init__(self, root): | |
| self._root = pathlib.Path(root) | |
| def __repr__(self): | |
| return f"{type(self).__name__}({str(self._root)!r})" | |
| def __len__(self): | |
| return sum(1 for _ in self) | |
| def __contains__(self, key): | |
| return (self._root / key).is_file() | |
| def __iter__(self): | |
| for subitem in self._root.iterdir(): | |
| if subitem.is_file(): | |
| yield subitem.name | |
| class SysFsNode(collections.abc.Mapping): | |
| def __init__(self, path): | |
| self._root = pathlib.Path(path) | |
| def __repr__(self): | |
| return f"{type(self).__name__}({str(self._root)!r})" | |
| def __getitem__(self, key): | |
| subitem = self._root / key | |
| if subitem.is_dir(): | |
| return type(self)(subitem) | |
| else: | |
| raise KeyError(f"Key {key} does not exist") | |
| def __iter__(self): | |
| for subitem in self._root.iterdir(): | |
| if subitem.is_dir(): | |
| yield subitem.name | |
| def __len__(self): | |
| return sum(1 for _ in self) | |
| def __contains__(self, key): | |
| return (self._root / key).is_dir() | |
| def __getattr__(self, name): | |
| try: | |
| return (self._root / name).read_text().strip() | |
| except FileNotFoundError: | |
| raise AttributeError(f"Attribute {name} does not exist") | |
| def attrs(self): | |
| return AttrsView(self._root) | |
| def __dir__(self): | |
| yield from super().__dir__() | |
| yield from self.attrs() | |
| root = SysFsNode('/sys') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment