rrd module to wrap rrdtool, providing a nicer command argument style
authorTero Marttila <terom@fixme.fi>
Sun, 06 Dec 2009 01:18:10 +0200
changeset 1 18787b57ba46
parent 0 6e664d3b7e63
child 2 a6bbe5cc24d7
rrd module to wrap rrdtool, providing a nicer command argument style
rrdweb/__init__.py
rrdweb/rrd.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rrdweb/rrd.py	Sun Dec 06 01:18:10 2009 +0200
@@ -0,0 +1,75 @@
+import rrdtool
+
+"""
+    Friendly wrapper around the rrdtool python interface
+"""
+
+def normalize_option_key (key) :
+    """
+        Normalize the given option key.
+
+        A -- is prepended, and _'s are converted to -
+    """
+
+    return '--' + str(key).replace('_', '-')
+
+def normalize_option_multi (key, values) :
+    """
+        Normalize a list of option values, returning a series of --opt, val1, --opt, val2, ...
+    """
+
+    for value in values :
+        yield key
+        yield str(value)
+
+def normalize_option (key, value) :
+    """
+        Normalize the given option to a series of cmd-args.
+
+        If value is None or False, no cmd-args are emitted. If value is True, only --opt is emitted. If value is a list,
+        --opt and value are emitted for each item.
+        
+        Otherwise, both --opt and str(value) are emitted.
+    """
+
+    key = normalize_option_key(key)
+
+    if value is None or value is False :
+        # omit
+        return ()
+
+    elif value is True :
+        # flag
+        return (key, )
+    
+    elif isinstance(value, list) :
+        # list of option values
+        return normalize_option_multi(key, value)
+
+    else :
+        # option value
+        return (key, str(value))
+
+def run_cmd (func, pre_args, opts, post_args) :
+    """
+        Run the given rrdtool.* function, formatting the given positional arguments and options.
+    """
+    
+    # series of (cmd-arg, cmd-arg, ...) tuples
+    opt_items = (normalize_option(key, value) for key, value in opts.iteritems())
+
+    # decomposed series of cmd-args
+    opt_args = [item for items in opt_items for item in items]
+
+    # positional arguments
+    pre_args = [str(arg) for arg in pre_args]
+    post_args = [str(arg) for arg in post_args]
+
+    # full arguments
+    args = pre_args + opt_args + post_args
+
+    return func(*args)
+
+def graph (out_path, *args, **opts) :
+    return run_cmd(rrdtool.graph, (out_path, ), opts, args)
+