Python:将脚本从过程转换为OOP样式

时间:2010-02-03 09:26:27

标签: python oop

我写了这个简单的Munin插件来绘制平均风扇速度图,我想重做它到OOP - 严格来说是一个学习练习。不知道从哪里开始。任何人都想提供一些指导,甚至是完成此脚本应该是什么样子的示例。我将使用它将一些其他脚本重做为OOP样式;再次出于学习目的。

import sys
import subprocess

CMD = "/usr/sbin/omreport chassis fans".split()

# Munin populates sys.argv[1] with "" (an empty argument), lets remove it.
sys.argv = [x for x in sys.argv if x]

if len(sys.argv) > 1:
    if sys.argv[1].lower() == "autoconfig":
        print "autoconfig"
    elif sys.argv[1].lower() == "config":
        print "graph_title Average Fan Speed"
        print "graph_args --base 1000 -l 0"
        print "graph_vlabel speed (RPM)"
        print "graph_category Chassis"
        print "graph_info This graph shows the average speed of all fans"
        print "graph_period second"
        print "speed.label speed"
        print "speed.info Average fan speed for the five minutes."
else:
    try:
        data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines()
    except OSError, e:
        print >> sys.stderr, "Error running '%s', %s" % (" ".join(cmd), e)
        sys.exit(1)

    count = total = 0
    for item in data:
        if "Reading" in item:
            # Extract variable length fan speed, without regex.
            total += int(item.split(":")[1].split()[0])
            count += 1
    # Sometimes omreport returns zero output if omsa services aren't started.
    if not count or not total:
        print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.'
        print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".'
        sys.exit(1)

    avg = (total / count)
    print "speed.value %s" % avg

1 个答案:

答案 0 :(得分:2)

通过识别合在一起的代码和数据,您可以在OOP中重新制作它。然后将这些合并到“类”中。

您上面的实际数据似乎是流程的输出。 代码正在迭代它。如果你愿意,我想你可以用它来制作课程,但这有点傻。 :)

所以,像这样(显然是完全未经测试的代码):

import sys
import subprocess

class Fanspeed(object):

    def __init__(self, command):
        self.command = command.split()

    def average_fan_speed(self):
        data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines()

        count = total = 0
        for item in data:
            if "Reading" in item:
                # Extract variable length fan speed, without regex.
                total += int(item.split(":")[1].split()[0])
                count += 1
        # Sometimes omreport returns zero output if omsa services aren't started.
        if not count or not total:
            raise ValueError("I found no fans. Is OMSA services started?"

        avg = (total / count)
        return % avg

if __main__ == '__main__':
    # Munin populates sys.argv[1] with "" (an empty argument), lets remove it.
    sys.argv = [x for x in sys.argv if x]

    if len(sys.argv) > 1:
        if sys.argv[1].lower() == "autoconfig":
            print "autoconfig"
        elif sys.argv[1].lower() == "config":
            print "graph_title Average Fan Speed"
            print "graph_args --base 1000 -l 0"
            print "graph_vlabel speed (RPM)"
            print "graph_category Chassis"
            print "graph_info This graph shows the average speed of all fans"
            print "graph_period second"
            print "speed.label speed"
            print "speed.info Average fan speed for the five minutes."
    else:
        try:
            cmd = "/usr/sbin/omreport chassis fans"
            fanspeed = Fanspeed(cmd)
            average = fanspeed.average_fan_speed()
        except OSError, e:
            print >> sys.stderr, "Error running '%s', %s" % (cmd, e)
            sys.exit(1)
        except ValueError, e:
            # Sometimes omreport returns zero output if omsa services aren't started.
            print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.'
            print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".'
            sys.exit(1)

但是YMMV。它可能更清楚一点。