#!/usr/bin/env python import subprocess import sys from optparse import OptionParser class SarMetric: def sarfetch(self, cmd, col): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) value = p.communicate()[0] return value.split('\n')[3].split()[col] def _get_user(self): ''' return %user value %user is in the 3rd colum of sar output ''' cmd = 'sar 1' col = -6 return self.sarfetch(cmd, col) def _get_nice(self): ''' return %nice value %nice is in the 4th colum of sar output ''' cmd = 'sar 1' col = -5 return self.sarfetch(cmd, col) def _get_system(self): ''' return %system value %system is in the 5th colum of sar output ''' cmd = 'sar 1' col = -4 return self.sarfetch(cmd, col) def _get_iowait(self): ''' return iowait value iowait value is in 6th column of sar output ''' cmd = 'sar 1' col = -3 return self.sarfetch(cmd, col) def _get_steal(self): ''' return %steal value %steal is in the 7th column of sar output ''' cmd = 'sar 1' col = -2 return self.sarfetch(cmd, col) def _get_idle(self): ''' return %idle value %idle is in the 8th column of sar output ''' cmd = 'sar 1' col = -1 return self.sarfetch(cmd, col) def get_options(): parser = OptionParser() # use list comprehension to retrieve list of supported metrics # by finding functions of the class with _get_ appended supported_metrics = [ i[5:] for i in dir(sar) if i[:5]=="_get_"] (options, args) = parser.parse_args() metric = args[0] if not metric in supported_metrics: sys.exit('unsupported metric %s' %metric) return metric if __name__ == '__main__': sar = SarMetric() metric = get_options() handler_prefix = '_get_' handler = handler_prefix + metric value = getattr(sar, handler)() print value