9

procfs大家好,Linux 在和中有很多很棒的功能sysfs,并且类似的工具vmstat扩展了很多,但是我需要从各种这些系统中收集数据,并希望利用一个统一的 Python 实用程序而不是一起破解一个一堆不同的脚本。

为了做到这一点,我首先需要确定 Python 是否具有我需要充分解析/处理不同数据收集点的点点滴滴。所以,我的问题的本质:

是否已经有处理/解析sysfs对象的 python 模块?

我已经通过 Google、usenet 和各种论坛寻找过这样的野兽,但我还没有找到任何智能或实用的东西。所以,在我切出一个之前,我想我先在这里检查一下。

4

3 回答 3

4

试试这个:

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)

它没有以任何方式抛光,但 IIRC 可以工作:)

于 2011-03-10T19:12:55.397 回答
3

来自电影人的回答,但删除了 int() 铸件:

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(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):
            return open(p, 'r').read()[:-1]
        elif isdir(p):
            return SysFsObject(p)

任意转换为 int 是出乎意料的,甚至是危险的。例如,如果您要在 sysfs 中流行的任何 cpulist 文件上使用该代码,则在多处理器系统上将始终返回诸如“0-7”之类的字符串。然后有一天,有人在单核系统上使用您的代码并读取现在包含“0”的完全相同的 sysfs 文件返回一个 int。

换句话说,任何调用该代码并期望接收 sysfs(字符串)的本机数据类型的函数都必须显式转换为 str()。

于 2013-10-12T04:55:52.050 回答
1

不太确定为什么你需要特定的东西,它们大部分都是文本文件,你可以直接弄乱它们。
据我所知,没有任何 python 模块可以做到这一点。

于 2011-01-10T17:31:18.173 回答