daily pastebin goal
61%
SHARE
TWEET

Untitled

a guest Mar 18th, 2019 41 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import collections.abc
  2. import pathlib
  3.  
  4. __all__ = ('root',)
  5.  
  6.  
  7. class AttrsView(collections.abc.KeysView):
  8.     def __init__(self, root):
  9.         self._root = pathlib.Path(root)
  10.  
  11.     def __repr__(self):
  12.         return f"{type(self).__name__}({str(self._root)!r})"
  13.  
  14.     def __len__(self):
  15.         return sum(1 for _ in self)
  16.  
  17.     def __contains__(self, key):
  18.         return (self._root / key).is_file()
  19.  
  20.     def __iter__(self):
  21.         for subitem in self._root.iterdir():
  22.             if subitem.is_file():
  23.                 yield subitem.name
  24.  
  25.  
  26. class SysFsNode(collections.abc.Mapping):
  27.     def __init__(self, path):
  28.         self._root = pathlib.Path(path)
  29.  
  30.     def __repr__(self):
  31.         return f"{type(self).__name__}({str(self._root)!r})"
  32.  
  33.     def __getitem__(self, key):
  34.         subitem = self._root / key
  35.         if subitem.is_dir():
  36.             return type(self)(subitem)
  37.         else:
  38.             raise KeyError(f"Key {key} does not exist")
  39.  
  40.     def __iter__(self):
  41.         for subitem in self._root.iterdir():
  42.             if subitem.is_dir():
  43.                 yield subitem.name
  44.  
  45.     def __len__(self):
  46.         return sum(1 for _ in self)
  47.  
  48.     def __contains__(self, key):
  49.         return (self._root / key).is_dir()
  50.  
  51.     def __getattr__(self, name):
  52.         try:
  53.             return (self._root / name).read_text().strip()
  54.         except FileNotFoundError:
  55.             raise AttributeError(f"Attribute {name} does not exist")
  56.  
  57.     def attrs(self):
  58.         return AttrsView(self._root)
  59.  
  60.     def __dir__(self):
  61.         yield from super().__dir__()
  62.         yield from self.attrs()
  63.  
  64.  
  65. root = SysFsNode('/sys')
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top