From 483c6874c075f93b40773343cd63772fc3ba8305 Mon Sep 17 00:00:00 2001 From: Wirawan Purwanto Date: Wed, 14 Sep 2016 13:39:55 -0400 Subject: [PATCH] * Use getopt to handle command-line option. * Include a help command. --- sge/show-cluster-usage.py | 58 +++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/sge/show-cluster-usage.py b/sge/show-cluster-usage.py index 29f95a0..e4ba81d 100755 --- a/sge/show-cluster-usage.py +++ b/sge/show-cluster-usage.py @@ -27,6 +27,14 @@ import re import subprocess import sys +class ParseError(RuntimeError): + pass + +class ProgramError(RuntimeError): + pass + +MYSELF = 'show-cluster-usage.py' + def analyze_cluster_usage_by_users(qstat_f): """Provides a summary analysis of cluster usage by users. @@ -91,20 +99,60 @@ def print_cluster_usage_by_users(usage): len(urec['xjobids']))) +def help(): + msg = """\ +%(CMD)s - Shows cluster usage from SGE information -def main_default(save_qstat=True): +The information is mainly drawn from `qstat -f` output, +and analyzes the usage of the cluster in various ways.. + +Usage: + +%(CMD)s +%(CMD)s [qstat_file] [--save] + Shows the cluster usage aggregated per user. +""" \ + % dict(CMD=MYSELF) + print(msg) + + +def main_default(argv): """Main default function: - By default we invoke qstat -f and prints the analysis. - If argv[1] is given, then we read in the file and use that for the analysis. """ from time import localtime, strftime + from getopt import getopt, GetoptError dtime = localtime() dtimestr = strftime("%Y%m%d-%H%M", dtime) - if len(sys.argv) > 1: - qstat_f_current = open(sys.argv[1], "r").read().splitlines() + # Skip program name and first command: + cmdargs_in = argv[1:] + try: + cmdopts, cmdargs = getopt(cmdargs_in, + "hs", + ["save", + "help"]) + except GetoptError as err: + sys.stderr.writelines([str(err), "\n"]) + return 2 + + # Process flag arguments + show_disabled_nodes = False + save_qstat = False + for o,a in cmdopts: + if o in ('-h', '--help'): + help() + return 0 + elif o in ('-s', '--save'): + save_qstat = True + else: + raise ProgramError, "Unhandled option in main program: %s %s" % (o,a) + + if len(cmdargs) > 1: + qstat_f_current = open(cmdargs[1], "r").read().splitlines() else: qstat_f_current = pipe_out(('qstat', '-f'), split=True) if save_qstat: @@ -114,7 +162,7 @@ def main_default(save_qstat=True): summary = analyze_cluster_usage_by_users(qstat_f_current) print_cluster_usage_by_users(summary) - + return 0 # --------------------------------------------------------------------------- @@ -164,4 +212,4 @@ def str_fmt_heading(fmt): # stub main code if __name__ == "__main__" and not "get_ipython" in globals(): - main_default() + sys.exit(main_default(sys.argv))