From 8cab221f6927bc088c72df21533f37233c59b8a2 Mon Sep 17 00:00:00 2001 From: Rob MacKinnon Date: Fri, 13 May 2022 13:36:35 -0700 Subject: [PATCH] Updated path handling to pathlib - Applied LICENSE file name correction (PR #7) - Added python __license__ variable - Updated .gitignore to include SublimeText IDE - Refactored using Python >3.4 Pathlib library for handling of Node pathing and remove usage of OS library. --- .gitignore | 1 + LICENCE => LICENSE | 0 sysfs/__init__.py | 32 ++++++++++++++++---------------- 3 files changed, 17 insertions(+), 16 deletions(-) rename LICENCE => LICENSE (100%) diff --git a/.gitignore b/.gitignore index 0662a9b..1836bc0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ /dist/ /*.egg*/ /.idea/ +/.sublime/ diff --git a/LICENCE b/LICENSE similarity index 100% rename from LICENCE rename to LICENSE diff --git a/sysfs/__init__.py b/sysfs/__init__.py index d253cc6..0557e5f 100644 --- a/sysfs/__init__.py +++ b/sysfs/__init__.py @@ -14,33 +14,33 @@ """ __all__ = ['sys', 'Node'] +__license__ = "MIT" -from os import listdir -from os.path import isdir, isfile, join, realpath, basename +from pathlib import Path, PosixPath class Node(object): __slots__ = ['_path_', '__dict__'] - def __init__(self, path='/sys'): - self._path_ = realpath(path) - if not self._path_.startswith('/sys/') and not '/sys' == self._path_: + def __init__(self, path: str='/sys'): + self._path_ = Path(path).resolve() + if not str(self._path_).startswith('/sys') and Path(self._path_).is_dir(): raise RuntimeError('Using this on non-sysfs files is dangerous!') - self.__dict__.update(dict.fromkeys(listdir(self._path_))) + self.__dict__.update(dict.fromkeys([_ for _ in self._path_.iterdir()])) def __repr__(self): return '' % self._path_ def __str__(self): - return basename(self._path_) + return self._path_.name - def __setattr__(self, name, val): + def __setattr__(self, name: str, val): if name.startswith('_'): return object.__setattr__(self, name, val) - path = realpath(join(self._path_, name)) - if isfile(path): - with open(path, 'w') as fp: + path = self._path_ / name + if path.is_file(): + with path.open('w') as fp: fp.write(val) else: raise RuntimeError('Cannot write to non-files.') @@ -49,11 +49,11 @@ def __getattribute__(self, name): if name.startswith('_'): return object.__getattribute__(self, name) - path = realpath(join(self._path_, name)) - if isfile(path): - with open(path, 'r') as fp: + path = self._path_ / name + if path.is_file(): + with path.open('r') as fp: return fp.read().strip() - elif isdir(path): + elif path.is_dir(): return Node(path) def __setitem__(self, name, val): @@ -63,7 +63,7 @@ def __getitem__(self, name): return getattr(self, name) def __iter__(self): - return iter(getattr(self, name) for name in listdir(self._path_)) + return iter(getattr(self, name) for name in self._path_.iterdir()) sys = Node()