Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python module to parse Linux's sysfs?

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.

like image 819
C.J. Steele Avatar asked Jan 10 '11 16:01

C.J. Steele


1 Answers

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 :)

like image 160
filmor Avatar answered Sep 24 '22 21:09

filmor