#!/usr/bin/env python # # pystat.py - print the latest vmstat output # import sys, getopt, time, os, signal from subprocess import * def usage(): print "Usage: pystat.py [-c NUM] [-i INTERVAL] [-o FILE] [-pPtT]" print print "Options:" print " -c NUM print the latest NUM lines of vmstat output" print " -i INTERVAL print at intervals of the INTERVAL seconds" print " -o FILE write to FILE instead of stdout" print " -p print top header" print " -P print top header and 5 processes" print " -t print with timestamp" print " -T print with the status of thermometer" sys.exit(0) def sighandler(sig, frame): try: os.kill(vmstat.pid, 15) except: pass sys.exit(0) try: opts, args = getopt.getopt(sys.argv[1:], "c:i:o:pPtT") except getopt.GetoptError: usage() opt_c = 5 opt_i = "5" opt_o = None opt_p, opt_P = (False, False) opt_t, opt_T = (False, False) for (opt, val) in opts: if opt == "-c": try: if int(val) > 0: opt_c = int(val) else: usage() except ValueError: usage() elif opt == "-i": try: if int(val) > 0: opt_i = val else: usage() except ValueError: usage() elif opt == "-o": opt_o = val elif opt == "-p": opt_p = True elif opt == "-P": opt_P = True elif opt == "-t": opt_t = True elif opt == "-T": opt_T = True else: usage() if len(args) > 0: usage() cmd = "vmstat -n " + opt_i vmstat = Popen(cmd, shell=True, stdout=PIPE) vm = vmstat.stdout signal.signal(15, sighandler) if opt_t: t = " " else: t = "" header = t + vm.readline() header += t + vm.readline() queue = [] t = "" while True: try: l = vm.readline() if opt_t: t = time.strftime("%F %T ") queue.append(t + l) if len(queue) > opt_c: queue.pop(0) output = header + ''.join(queue) if opt_T: sens = Popen("sensors | grep ^temp", shell=True, stdout=PIPE).stdout for l in sens: output += t + l sens.close() if opt_P: top = Popen("top -bn1 | head -n 12", shell=True, stdout=PIPE).stdout for l in top: output += t + l.rstrip(" \n") + "\n" top.close() elif opt_p: top = Popen("top -bn1 | head -n 5", shell=True, stdout=PIPE).stdout for l in top: #output += t + l.rstrip(" \n") + "\n" output += t + l top.close() if opt_o: out = open(opt_o, "w") out.write(output) out.close() else: print output, except KeyboardInterrupt: break vm.close()