optparse and counting arguments (not options)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Steven Bethard

    optparse and counting arguments (not options)

    I feel like I must be reinventing the wheel here, so I figured I'd post
    to see what other people have been doing for this. In general, I love
    the optparse interface, but it doesn't do any checks on the arguments.
    I've coded something along the following lines a number of times:

    class OptionArgParser (optparse.Optio nParser):
    def __init__(self, *args, **kwargs):
    self.min_args = kwargs.pop('min _args', None)
    self.max_args = kwargs.pop('max _args', None)
    self.arg_values = kwargs.pop('arg _values', None)
    optparse.Option Parser.__init__ (self, *args, **kwargs)

    def parse_args(self , args=None):
    options, args = optparse.Option Parser.parse_ar gs(self, args)
    if self.min_args is not None and len(args) < self.min_args:
    self.error('too few arguments')
    if self.max_args is not None and len(args) > self.max_args:
    self.error('too many arguments')
    if self.arg_values is not None:
    for arg, values in zip(args, self.arg_values ):
    if values is not None and arg not in values:
    message = 'argument %r is not one of: %s'
    self.error(mess age % (arg, ', '.join(values)) )
    return options, args

    This basically lets me skip some simple checks by creating instances of
    OptionArgParser instead of optparse.Option Parser, and supplying my new
    options:

    parser = OptionArgParser (
    min_args=1, arg_values=[commands],
    usage='%%prog [options] (%s) ...' % '|'.join(comman ds),
    description='in voke one of the commands')

    Is this problem already solved in some module that I've missed?

    STeVe
Working...