Hey all, Linux has a lot of great features in procfs
and sysfs
, and tools like vmstat
extend that quite a bit, but I have a need to collect data from a variety of these systems and was hoping to leverage a unified Python utility instead of hacking together a bunch of disparate scripts.
In order to do that I first need to identify whether or not Python has the bits and pieces I need to adequately parse/process the different data collection points. So, the essence of my question:
Is there a python module that handles/parses the sysfs
objects already?
I've looked for such a beast via Google, usenet, and various forums, but I haven't yet found anything intelligent or functional. So, before I carve one out, I figured I'd check here first.
Try this one:
from os import listdir
from os.path import isdir, isfile, islink, join, realpath, normpath
from keyword import iskeyword
_norm = lambda name: name + ('_' if iskeyword(name) else '')
def _denorm(name):
if name.endswith('_') and iskeyword(name[:-1]):
return name[:-1]
else:
return name
def _norm_path(path):
return normpath(realpath(path))
class SysFsObject(object):
__slots__ = ['_path', '__dict__']
@staticmethod
def __id_args__(path='/sys'):
return _norm_path(path)
def __init__(self, path='/sys'):
self._path = _norm_path(path)
if not self._path.startswith('/sys'):
raise RuntimeError("Using this on non-sysfs files is dangerous!")
self.__dict__.update(dict.fromkeys(_norm(i) for i in listdir(self._path)))
def __repr__(self):
return "<SysFsObject %s>" % self._path
def __setattr__(self, name, val):
if name.startswith('_'):
return object.__setattr__(self, name, val)
name = _denorm(name)
p = realpath(join(self._path, name))
if isfile(p):
file(p, 'w').write(str(val))
else:
raise RuntimeError
def __getattribute__(self, name):
if name.startswith('_'):
return object.__getattribute__(self, name)
name = _denorm(name)
p = realpath(join(self._path, name))
if isfile(p):
data = open(p, 'r').read()[:-1]
try:
return int(data)
except ValueError:
return data
elif isdir(p):
return SysFsObject(p)
It's not polished in any way, but IIRC it works :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With