optparse and counting arguments (not options)

Discussion in 'Python' started by Steven Bethard, May 10, 2006.

  1. 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.OptionParser):
    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.OptionParser.__init__(self, *args, **kwargs)

    def parse_args(self, args=None):
    options, args = optparse.OptionParser.parse_args(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(message % (arg, ', '.join(values)))
    return options, args

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

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

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

    STeVe
    Steven Bethard, May 10, 2006
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Goodger

    Re: Iterating over optparse options

    David Goodger, Jun 25, 2003, in forum: Python
    Replies:
    0
    Views:
    980
    David Goodger
    Jun 25, 2003
  2. Gregory (Grisha) Trubetskoy

    Required options in optparse

    Gregory (Grisha) Trubetskoy, Oct 4, 2003, in forum: Python
    Replies:
    0
    Views:
    413
    Gregory (Grisha) Trubetskoy
    Oct 4, 2003
  3. Rocky Zhou
    Replies:
    3
    Views:
    300
    Steven Bethard
    Mar 18, 2007
  4. Omari Norman

    Re: optparse - required options

    Omari Norman, Aug 23, 2007, in forum: Python
    Replies:
    2
    Views:
    419
    Steve Holden
    Aug 24, 2007
  5. Ben Woodcroft
    Replies:
    2
    Views:
    154
    Ben Woodcroft
    May 20, 2009
Loading...

Share This Page