diff --git a/optparse.rst b/optparse.rst index 3d8b43c..032d413 100644 --- a/optparse.rst +++ b/optparse.rst @@ -1625,36 +1625,43 @@ directly). Nevertheless, here's a stab at a callback for an option with variable arguments:: - def vararg_callback(option, opt_str, value, parser): - assert value is None - done = 0 - value = [] - rargs = parser.rargs - while rargs: - arg = rargs[0] - - # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f", - # etc. Note that this also stops on "-3" or "-3.0", so if - # your option takes numeric values, you will need to handle - # this. - if ((arg[:2] == "--" and len(arg) > 2) or - (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): - break - else: - value.append(arg) - del rargs[0] - - setattr(parser.values, option.dest, value) + def vararg_callback(option, opt_str, value, parser): + assert value is None + value = [] + rargs = parser.rargs + def floatable(str): + try: + float(str) + return True + except ValueError: + return False + + def check_vararg(arg): + '''Return false) if we hit an arg like "--foo", "-a", "-fx", + "--file=f", etc. Allows negative numbers and floats (-3.0) to + pass through unmolested. ''' + # --foo like options + if arg == "-": + return False + if (arg[:2] == "--" and len(arg) > 2): + return False + # -a means stop, -3.0 is okay. + if (arg[:1] == "-" and len(arg) > 1 and not floatable(arg)): + return False + return True + + for arg in rargs: + if check_vararg(arg): + value.append(arg) + else: + break + + setattr(parser.values, option.dest, value)) [...] parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback) -The main weakness with this particular implementation is that negative numbers -in the arguments following ``"-c"`` will be interpreted as further options -(probably causing an error), rather than as arguments to ``"-c"``. Fixing this -is left as an exercise for the reader. - .. _optparse-extending-optparse: