# HG changeset patch # User Tero Marttila # Date 1260055090 -7200 # Node ID 18787b57ba460df72085130861a969e5c31c2530 # Parent 6e664d3b7e6369d2d5c92814dec8124fe8643340 rrd module to wrap rrdtool, providing a nicer command argument style diff -r 6e664d3b7e63 -r 18787b57ba46 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) +